0

I've a byte. What I want to do is access bit position to retrieve boolean (0 or 1). How can I do that in Kotlin?

fun getBit(b: Byte, bitNumber: Int): Boolean {
    val shift: Int = 7 - bitNumber
    val bitMask = (1 shl shift).toByte()

    val masked = (b and bitMask)
    return masked.toInt() != 0
}

This for some reason return incorrect value of false when it should return true

MaaAn13
  • 264
  • 5
  • 24
  • 54

1 Answers1

2

Your algorithm seems OK, I think you just made an off by one error (although you didn't say if you are counting from 0 or 1). If I change it to

val shift: Int = 8 - bitNumber

It seems to work fine for me:

fun getBit(b: Byte, bitNumber: Int): Boolean {
    require(bitNumber in 1..8)
    val shift: Int = 8 - bitNumber
    val bitMask = (1 shl shift).toByte()

    val masked = (b and bitMask)
    return masked.toInt() != 0
}

fun main() {
    println(getBit(0b10000000.toByte(), 1))
    println(getBit(0b10000000.toByte(), 2))
    println(getBit(0b01000000, 2))
}

Output:

true
false
true

Note: you can avoid the experimental Byte.and() by using Int.and() instead:

val bitMask = (0b1 shl shift)
val masked = (b.toInt() and bitMask)
return masked != 0
Adam Millerchip
  • 20,844
  • 5
  • 51
  • 74