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 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));
Converting from byte to int in Java
Your array is of byte
primitives, but you're trying to call a method on them.
You don't need to do anything explicit to convert a byte
to an int
, just:
int i=rno[0];
...since it's not a downcast.
Note that the default behavior of byte
-to-int
conversion is to preserve the sign of the value (remember byte
is a signed type in Java). So for instance:
byte b1 = -100;
int i1 = b1;
System.out.println(i1); // -100
If you were thinking of the byte
as unsigned (156) rather than signed (-100), as of Java 8 there's Byte.toUnsignedInt
:
byte b2 = -100; // Or `= (byte)156;`
int = Byte.toUnsignedInt(b2);
System.out.println(i2); // 156
Prior to Java 8, to get the equivalent value in the int
you'd need to mask off the sign bits:
byte b2 = -100; // Or `= (byte)156;`
int i2 = (b2 & 0xFF);
System.out.println(i2); // 156
Just for completeness #1: If you did want to use the various methods of Byte
for some reason (you don't need to here), you could use a boxing conversion:
Byte b = rno[0]; // Boxing conversion converts `byte` to `Byte`
int i = b.intValue();
Or the Byte
constructor:
Byte b = new Byte(rno[0]);
int i = b.intValue();
But again, you don't need that here.
Just for completeness #2: If it were a downcast (e.g., if you were trying to convert an int
to a byte
), all you need is a cast:
int i;
byte b;
i = 5;
b = (byte)i;
This assures the compiler that you know it's a downcast, so you don't get the "Possible loss of precision" error.
Converting integer array to byte array
convert int to byte[].
create this function:
byte[] toBytes(int i)
{
byte[] result = new byte[4];
result[0] = (byte) (i >> 24);
result[1] = (byte) (i >> 16);
result[2] = (byte) (i >> 8);
result[3] = (byte) (i /*>> 0*/);
return result;
}
Run in a loop on your int[], for each cell call to the function and add result to an array of bytes.
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 int
s 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 byte
s or as 2 short
s, 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.
Converting byte array to int array in Java, via ByteBuffer to IntBuffer, without truncating
Hi you can try this if you do not need to use IntBuffer.
byte[] plainTextBytes = "Hello World".getBytes();
int[] ints = new int[plainTextBytes.length];
for(int i = 0; i < ints.length; i++){
ints[i] = plainTextBytes[i];
}
You basically convert bytes directly into ints.
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
}
Related Topics
Compare One String with Multiple Values in One Expression
How to Use "Cd" Command Using Java Runtime
Is Calling Static Methods via an Object "Bad Form"? Why
What Are the Best Use Cases for Akka Framework
Having a 3Rd Party Jar Included in Maven Shaded Jar Without Adding It to Local Repository
Loading Raw 64-Byte Long Ecdsa Public Key in Java
Handling Java Crypto Exceptions
Performance of Javafx Gui VS Swing
What Is the Purpose of Defining a Package in a Java File
Javabean Wrapping with Javafx Properties
Checked VS Unchecked Exception
Spring Qualifier and Property Placeholder
Java.Lang.Outofmemoryerror: Java Heap Space in Maven
Rounding a Double to Turn It into an Int (Java)
How Many Threads Are Spawned in Parallelstream in Java 8
How to Read Request Body Multiple Times in Spring 'Handlermethodargumentresolver'