Reputation: 7437
Why does a double
of 65555
converted to byte
produce a result of 19
in Kotlin?
Upvotes: 3
Views: 397
Reputation: 147991
That's because of a numerical conversion from a wider type to a type of a smaller size. The Double
(IEEE 754 double precision number) has its integral part factored to the powers of two as
65555 = 217 + 24 + 22 + 20 = 65536 + 16 + 2 + 1, which is stored in binary form as (higher bits to lower):
... 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 lowest 8 bits are retained:
... _ _ _ _ _ _ _ _ _ _ 0 0 0 1 0 0 1 1
And that results into 24 + 22 + 20 = 16 + 2 + 1 = 19.
Upvotes: 9
Reputation: 31710
Because when you convert 65555 (or 65555.0) to a binary representation it takes more than one byte. So calling .toByte()
takes the lowest one, which is 19.
65555 -> Binary == 1 00000000 00010011
^ ^^^^^^^^ ^^^^^^^^
1 0 19
Upvotes: 3
Reputation: 6373
Double 65555.0 gets converted to integer 65555 which is 0x10013. Conversion to Byte takes lower byte which is 0x13 (19 decimal).
Upvotes: 1