The byteValue() method of Integer class of java. lang package converts the given Integer into a byte after a narrowing primitive conversion and returns it (value of integer object as a byte).
An int value can be converted into bytes by using the method int. to_bytes(). The method is invoked on an int value, is not supported by Python 2 (requires minimum Python3) for execution.
Yes you do. For bytes, you can only assign literals and constants between -128 and 127. Any other number, you need an explicit cast.
using Java NIO's ByteBuffer is very simple:
byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();
for (byte b : bytes) {
System.out.format("0x%x ", b);
}
output:
0x65 0x10 0xf3 0x29
How about:
public static final byte[] intToByteArray(int value) {
return new byte[] {
(byte)(value >>> 24),
(byte)(value >>> 16),
(byte)(value >>> 8),
(byte)value};
}
The idea is not mine. I've taken it from some post on dzone.com.
BigInteger.valueOf(1695609641).toByteArray()
byte[] IntToByteArray( int data ) {
byte[] result = new byte[4];
result[0] = (byte) ((data & 0xFF000000) >> 24);
result[1] = (byte) ((data & 0x00FF0000) >> 16);
result[2] = (byte) ((data & 0x0000FF00) >> 8);
result[3] = (byte) ((data & 0x000000FF) >> 0);
return result;
}
Using Guava:
byte[] bytearray = Ints.toByteArray(1695609641);
byte[] conv = new byte[4];
conv[3] = (byte) input & 0xff;
input >>= 8;
conv[2] = (byte) input & 0xff;
input >>= 8;
conv[1] = (byte) input & 0xff;
input >>= 8;
conv[0] = (byte) input;
public static byte[] intToBytes(int x) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(bos);
out.writeInt(x);
out.close();
byte[] int_bytes = bos.toByteArray();
bos.close();
return int_bytes;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With