0

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

1

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

4 Comments

Try fold(0) { acc, int -> (acc shl 1) or int }. It seems to be drastically faster. Why I do not know.
@lukas.j Cannot reproduce, it seems to be slightly faster with fold (19 nanoseconds) - pl.kotl.in/3NbDzG0VO
It seems to be rather quite a lot of faster when running that in the playground too. reduce takes at leats 50% longer than fold.
Looking at the generated Kotlin bytecode it seems that reduce creates an IntIterator while fold uses a 'goto-loop'. That might explain why fold is faster.
1

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

Note that @adnan_e's solutions is faster than this one.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.