Home > Mobile >  How to convert a array of bits to a byte, (not to byte string)?
How to convert a array of bits to a byte, (not to byte string)?

Time:01-08

I have the follow array:

val cells = arrayOf(
  0b1, 0b1, 0b1,
  0b0, 0b0, 0b0,
  0b0, 0b0, 0b0,
)

And I want to convert it to number e.g: 0b111000000, to be able to compare with another byte after:

val cells = arrayOf(
  0b1, 0b1, 0b1,
  0b0, 0b0, 0b0,
  0b0, 0b0, 0b0,
)

print(arrayOfBitsToByte(cells) == 0b111000000)

I could make this:

val cells = arrayOf(
  0b1, 0b1, 0b1,
  0b0, 0b0, 0b0,
  0b1, 0b1, 0b1,
)

print(cells.joinToString("") == 0b111000000.toString(2))

But in the above case, the 2 values were cast to String

And I would like to know if it is possible to compare the numbers without cast to string

CodePudding user response:

Convert the array of bits into a single Int using bitwise operations. This assumes that each element is either 0 or 1, and will break otherwise (due to only shifting by 1 bit).

val cells = arrayOf(
        0b1, 0b1, 0b1,
        0b0, 0b0, 0b0,
        0b0, 0b0, 0b0,
)

var joined = cells.reduce{ acc, curr -> ((acc shl 1) or curr) }
print(joined == 0b111000000)

CodePudding user response:

Simple conversion of the array to an int (avoiding bitwise operations):

import kotlin.math.pow

val cells = arrayOf(
    0b1, 0b1, 0b1,
    0b0, 0b0, 0b0,
    0b1, 0b1, 0b1,
)

fun Array<Int>.toInt() = this
    .foldIndexed(0) { index, acc, int ->
      acc   if (int == 0b1) 2.0.pow(index).toInt() else 0
    }

println(cells.toInt() == 0b111000000)   // false
println(cells.toInt() == 0b111000111)   // true
  • Related