Home > other >  Access two first bytes in byte array
Access two first bytes in byte array

Time:10-27

I have a variable of type ByteArray:

val byteArray: ByteArray?

I am currently accessing its first byte, indexing it as follows: byteArray[0]. I want to be able to get the first two bytes on this byte array. Should I get byte 0 and 1 and then append, or can I do byteArray[0:1] somehow? I am very new to Java and Kotlin and any guidance is appreciated.

I need to be able to get the first two bytes , so then I can get bits 0 to 16 and convert it to an integer. I use this to convert bytes to binary string:

  `String.format("%8s", Integer.toBinaryString(inByte & 0xFF)).replace(' ', '0');`

CodePudding user response:

If you want an integer from the first two bytes, just use a ByteBuffer:

// x is of type Short
val x = ByteBuffer.wrap(byteArray).short

This will only read the first two bytes of the array, in big endian order (you can change this with order), or throw an exception if there are fewer than 2 bytes in the array.

CodePudding user response:

You can use destructuring to access the first two bytes in an array.

To convert them to an integer, you can use toInt to convert the first byte, shl to bitshift it left by 8 bits, and then add the 2nd byte.

fun main() {
    val byteArray = byteArrayOf(0b00000001, 0b00000010, 0b00000011)
    val (firstByte, secondByte) = byteArray.toUByteArray()
    val firstTwoBytes = (firstByte.toInt() shl 8)   secondByte.toInt()
    println(firstByte)      // 00000001
    println(secondByte)     // 00000010
    println(firstTwoBytes)  // 0000000100000010
}

Output:

1
2
258

I am converting the signed byte array toUByteArray() here, because toInt() preserves the numeric value of the signed bytes, meaning negative bytes would produce negative integers, which is not what you want if you are only concerned with the raw bits. Using unsigned bytes is what you really want here.

If you wanted to avoid converting the whole array, you could convert only the first two bytes by doing this instead:

val firstTwoBytes = (firstByte.toUByte().toInt() shl 8)   secondByte.toUByte().toInt()

CodePudding user response:

You did not specify the order of the bits in your bytes. Depending on whether you want big endian or small endian use

int result = ((int)byteArray[1])*256 ((int)byteArray[0])

or

int result = ((int)byteArray[2])*256 ((int)byteArray[1])

CodePudding user response:

Big Endian

byte[] bytes = new byte[] { 1, 2, 3, 4 };
int shorty = ((bytes[0] & 0xFF) << 8) | (bytes[1] & 0xFF);

Little Endian

byte[] bytes = new byte[] { 1, 2, 3, 4 };
int shorty = ((bytes[1] & 0xFF) << 8) | (bytes[0] & 0xFF);
  • Related