https://kotlinlang.org logo
m

Muhammet Emin Gündoğar

05/25/2022, 8:35 PM
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

ephemient

05/25/2022, 8:38 PM
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

Muhammet Emin Gündoğar

05/25/2022, 9:03 PM
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

Landry Norris

05/25/2022, 9:11 PM
inv() makes it 0b11111111….1110
e

ephemient

05/25/2022, 9:11 PM
0x01.inv() == 0xFFFFFFFE.toInt()
l

Landry Norris

05/25/2022, 9:12 PM
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

Muhammet Emin Gündoğar

05/25/2022, 9:13 PM
ok i got it now thank you both
l

Landry Norris

05/25/2022, 9:13 PM
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

Muhammet Emin Gündoğar

05/25/2022, 9:14 PM
but there is a thing
why did not coder write 0x1 instead
both are same
0x01 and 0x1
l

Landry Norris

05/25/2022, 9:14 PM
I’ve done (this - this % 2) before for floor even.
e

ephemient

05/25/2022, 9:14 PM
same as writing
1.inv()
as well
m

Muhammet Emin Gündoğar

05/25/2022, 9:15 PM
yeah both works
e

ephemient

05/25/2022, 9:15 PM
but hex numbers are usually written with an even number of digits, because each pair is one byte
👍 1
l

Landry Norris

05/25/2022, 9:15 PM
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

Muhammet Emin Gündoğar

05/25/2022, 9:16 PM
it is kinda naming convention?
e

ephemient

05/25/2022, 9:17 PM
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
6 Views