Is `x and 0xFF.toByte()` a noop? Aka `x and 0xFF.t...
# getting-started
r
Is
x and 0xFF.toByte()
a noop? Aka
x and 0xFF.toByte() == x
is always true?
j
What type is
x
?
r
Also
Byte
j
Then I indeed don't quite get the point of this 🤔 Should be a noop IMO. But I'm not well versed in Kotlin's bitwise operators
If this code is old, it might come from the days when Kotlin didn't have bitwise operators on Bytes and you had to convert to
Int
to do this 🤷
r
I pasta'd it from Java code, where it was on `Int`s
j
Ah, then forget about my last point
s
Can you share the Java code? Typically
& 0xFF
would be used to truncate the sign bits or other unwanted extras. Translating it to Kotlin probably requires some understanding of the intended behaviour.
And Kotlin has unsigned types which might or might not make your life easier
j
response.getData()[0]
is already a byte, though. I'm not sure what the Java code wanted to do initially with this
s
I imagine the intention is to print the byte as if it is an unsigned value.
j
but I fail to see what difference it makes to
& 0xFF
(even in terms of sign bits) if the original value is a byte
s
0xFF
in Java is an int, because it is too big to be a signed byte
🙏 1
Consider this Java code:
Copy code
byte signed = -1;
System.out.println("Signed value is " + signed);
// Signed value is -1
int unsigned = 0xFF & signed;
System.out.println("Unsigned value is " + unsigned);
// Unsigned value is 255
j
Got it, I missed that
& 0xFF
also converts the original value to
int
before truncating the bits
s
As for the Kotlin equivalent:
Copy code
val data: Byte = -1
println("Signed value is " + data)
println("Unsigned value is " + data.toUByte())
(or
data.toUByte().toInt()
if you want to match the Java version more exactly)
👍 1