Extracting Raw Data from Integer and Long Variables in Java

97 views Asked by At

I'm working on a Java project where I have been tasked with extracting raw data from both integer and long variables.

Here's an input:

Integer intValue = 42;
Long longValue = 9876543210L;

How can I extract the raw data as bytes from intValue and longValue?

1

There are 1 answers

10
John Williams On BEST ANSWER

For integer

byte[] bytes = ByteBuffer.allocate(Integer.BYTES).putInt(42).array();

for (byte b : bytes) {
   System.out.format("0x%x ", b);
}

For long

byte[] bytes = ByteBuffer.allocate(Long.BYTES).putLong(9876543210L).array();

for (byte b : bytes) {
   System.out.format("0x%x ", b);
}

The above prints in hexadecimal format. To print each byte as 0/1 style bits use:

   System.out.format(String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0'));