```fun Int.floorEven() = this and 0x01.inv()``` I ...
# kotlin-native
m
Copy code
fun Int.floorEven() = this and 0x01.inv()
I was reading a project and i saw this code but i could not understand why this code flooring the number to even i know 01 inverse equals to -2 because of 2's complement equals to 1's complement - 1 and 2 complent is negative of that number but i could not understand why this code will always work?
😶 1
e
it clears the lowest bit and that is equivalent to flooring to even. consider that
this shr 1 shl 1
is equivalent to
this.floorDiv(2) * 2
which also clears the lowest bit.
m
Firstly correct me if i am wrong 0x used as a prefix for hexadecimal numbers right?And that's why 0x01 means 01 and inv() just makes it 10 anding with any number will clear least significant bit.But i also tried 0x10 without inv method but it did not work.Can you explain why? @ephemient
l
inv() makes it 0b11111111….1110
e
0x01.inv() == 0xFFFFFFFE.toInt()
l
But no one wants to type 31 1s, so it makes sense to do a 1.inv(). The 0x just makes it clear we’re doing bit math.
m
ok i got it now thank you both
l
When we do a bitwise and with 0b1111111…110, we end up with the most significant 31 bits getting and’ed with 1, and (x and 1) == x. The last gets and’ed with 0, and (x and 0) == 0.
m
but there is a thing
why did not coder write 0x1 instead
both are same
0x01 and 0x1
l
I’ve done (this - this % 2) before for floor even.
e
same as writing
1.inv()
as well
m
yeah both works
e
but hex numbers are usually written with an even number of digits, because each pair is one byte
👍 1
l
Just style. Hexadecimal is mainly used in bitmath, so the 0x makes it clear we’re doing bitmath. Some people, such as myself, like having an even number of digits.
m
it is kinda naming convention?
e
there are certainly exceptions, for example the space of Unicode codepoints is 21 bits
but usually we use hex to represent values that we are interpreting as bytes