Converting large numbers to bytes in Kotlin

Why is the conversion double

of 65555

in byte

leads to a result 19

in Kotlin?

+3


source to share


3 answers


This is due to the numerical conversion from a wider type to a smaller type. Double

( IEEE 754 double precision number ) has its integral part, counted in powers of two, like 65555 = 2 17 + 2 4 + 2 2 + 2 0 = 65536 + 16 + 2 + 1, which is stored in binary form (upper digits below):

 ‭... 0 1  0 0 0 0 0 0 0 0  0 0 0 1 0 0 1 1‬

      

When this number is converted to Byte

, only its lower 8 bits are kept:



 ... _ ‭_  _ _ _ _ _ _ _ _  0 0 0 1 0 0 1 1‬

      

And that leads to 2 4 + 2 2 + 2 0 = 16 + 2 + 1 = 19.

+9


source


Because when you convert 65555 (or 65555.0) to binary, more than one byte is required. Therefore, the call .toByte()

takes the lowest one, which is 19.



65555 -> Binary == 1 00000000 00010011
                   ^ ^^^^^^^^ ^^^^^^^^
                   1     0       19

      

+3


source


The double 65555.0 converts to the integer 65555, which is 0x10013. The conversion to byte takes the least significant byte, which is 0x13 (19 decimal places).

+1


source







All Articles