Convert a Byte Array to Integer in Java and Vice Versa

Convert a byte array to integer in Java and vice versa

Use the classes found in the java.nio namespace, in particular, the ByteBuffer. It can do all the work for you.

byte[] arr = { 0x00, 0x01 };
ByteBuffer wrapped = ByteBuffer.wrap(arr); // big-endian by default
short num = wrapped.getShort(); // 1

ByteBuffer dbuf = ByteBuffer.allocate(2);
dbuf.putShort(num);
byte[] bytes = dbuf.array(); // { 0, 1 }

Byte Array and Int conversion in Java

You're swapping endianness between your two methods. You have intToByteArray(int a) assigning the low-order bits into ret[0], but then byteArrayToInt(byte[] b) assigns b[0] to the high-order bits of the result. You need to invert one or the other, like:

public static byte[] intToByteArray(int a)
{
byte[] ret = new byte[4];
ret[3] = (byte) (a & 0xFF);
ret[2] = (byte) ((a >> 8) & 0xFF);
ret[1] = (byte) ((a >> 16) & 0xFF);
ret[0] = (byte) ((a >> 24) & 0xFF);
return ret;
}

How to convert byte array into integer value

Just use ByteBuffer.getInt():

int pomAsInt = ByteBuffer.wrap(pom).getInt();

How to convert a Byte Array to an Int Array without copying

No it is not possible.

Arrays in Java cannot be easily re-interpreted as other types. The memory layout for an array object includes a pointer to the array class, and the array's length. There are no operations that would allow you to overwrite the class pointer and the length field of an existing array.

You can do something similar using "buffer" objects from java.nio but it's not really the same. You can create a ByteBuffer object that wraps an array of bytes. You can then get an IntBuffer "view" from the byte buffer. No data is copied, as these objects are simply views that access data in the byte array. This prints out 0x64636261:

byte[] byte_array = new byte[128];
byte_array[0] = 'a'; // 0x61
byte_array[1] = 'b'; // 0x62
byte_array[2] = 'c'; // 0x63
byte_array[3] = 'd'; // 0x64

ByteBuffer byteBuffer = ByteBuffer.wrap(byte_array);
// set CPU-native byte order to enable optimizations
byteBuffer.order(ByteOrder.nativeOrder());

IntBuffer intBuffer = byteBuffer.asIntBuffer();
System.out.printf("0x%X\n", intBuffer.get(0));

What is the most efficient way to convert array of int to array of byte and vice versa?

In Java, a byte is 8 bits, while an int is 32 bits.

To convert each of your ints to a single byte without loss of data, you need to ensure all your numbers are in the range -128 to 127 inclusive.

If they are in this range, then you should just store them as bytes in the first place (if this is not possible, there are ways to do the conversion already discussed).

If they are not in this range, then you shouldn't be converting them to bytes at all because it will force your numbers into the range, and thus you will lose a lot of data.

Alternatively, you could use short, as that would be 16 bits (giving you the range -32,768 to 32,767 inclusive).

But if you can't ensure that your numbers will be within these ranges, then you will need to use int.


Note: You can store each int as 4 bytes or as 2 shorts, but each number would still be 32 bits, so you're not gaining any space efficiency by doing so.


You can read more about Java's primitive types here.

Java: ByteArray to positive number and vice versa conversion

Edit: just replace

String string = new BigInteger(originalBytes).toString();

with

String string = new BigInteger(1, originalBytes).toString();

The 1, signals that the passed array represents a positive number (signum = 1)

Original:

You can just prefix the array with a zero byte:

byte[] original = new byte[] { (byte) 255 };

System.out.println(new BigInteger(original).toString()); // prints "-1"

byte[] paddedCopy = new byte[original.length + 1];
for (int i = 0; i < original.length; i++) {
paddedCopy[i + 1] = original[i];
}
System.out.println(new BigInteger(paddedCopy).toString()); // prints "255"

This will essentially nullify the sign bit, making the number unsigned.

how to convert byte array to integer?

Just to clearify: You have a byte[] that contains pairs of byte's to form an integer? So like this: {int1B1, int1B2, int2B1, int2B2, int3B1, int3B2, ...}?

If so, you can assemble them to integers like this:

int[] audio = new int[byteArray.length/2];
for (int i = 0; i < byteArray.length/2; i++) { // read in the samples
int lsb = byteArray[i * 2 + 0] & 0xFF; // "least significant byte"
int msb = byteArray[i * 2 + 1] & 0xFF; // "most significant byte"
audio[i] = (msb << 8) + lsb;
}

Of course you can optimize that loop to a single line loop, but I prefer it that way for better readability. Also, depending on the endianness of the data, you can switch ub1 and ub2.

Convert Byte Array to Int odd result Java and Kotlin

As suggested by @Lother and itsme86.

fun littleEndianConversion(bytes: ByteArray): Int {
var result = 0
for (i in bytes.indices) {
result = result or (bytes[i].toInt() shl 8 * i)
}
return result
}

Convert byte array to integer

Try:

integers[i] = (int)bytes[i] & 0xff;

Java hex byte array converting to integer without converting to String first

Whilst it's very unclear why you would represent the data in this way, it's easy to transform without using a string:

int v = 0;
for (byte b : bytes) {
v = 16 * v + Character.getNumericValue(b);
}

Ideone demo



Related Topics



Leave a reply



Submit