Question

Possible Duplicate:
Java integer to byte array

Here's another question still related to the original below:

If I have a hex number that takes up 4 characters (2-bytes) saved as an integer. Example:

int value = 0xFFFF;

This in java will make it a 4-byte hex with 2 bytes being completely empty.

How am I able to grab only the two bytes that have data?

Help is greatly appreciated! :)

Answer to my second question:

Better answer posted below by md_5.

So to get the SINGLE byte that has data you can simply do: byte single = (byte) i & 0xFF If you had a bigger number up to 65535 (0xFFFF) you can do:

byte b1 = (byte) ((i >> 8) & 0xFF); 
byte b2 = (byte) i & 0xFF 

If you had an even larger number in the integer range you just do b1 = i >> 24, b2 = i >> 16, etc etc etc. Subtracting 8 from the shift as that is the size of a byte.

An alternate method uses the answer to the original question:

int hex = 0xF15E;
byte[] bytes = ByteBuffer.allocate(4).putInt(hex).array();
for(int i = 0; i < 4; i++) {
    System.out.format("0x%X ", bytes[i]);
}

Output:

0x0 0x0 0xF1 0x5E

So then take the important bytes:

byte[] importantBytes = {bytes[2], bytes[3]};

Original Question:

This question may be obsolete due to being able to converting an Integer into a byte[] but here goes:

How does one convert an integer into a hexidecimal that has leading 0's?

So if I have the integer: 4096, in hex would be 00001000.

The overall purpose was to then convert this formatted hex string into a byte[] (which would then be saved), but I think I can do this by the means above.

But still... How do we convert this integer into a formatted hex string? Is this even practical?

The language of preference is Java, and I looked at Integer.toHexString().

Working solution for what I originally needed:

int value = 2147483647;
byte[] bytes = ByteBuffer.allocate(4).putInt(value).array();

for(int i = 0; i < 4; i++)
System.out.format("0x%X ", bytes[i]);
Was it helpful?

Solution 2

In regards to your new question (getting the bytes that have data), you are wrong in saying that it takes up 2 bytes, 0xFF can in fact be packed into one byte. Long/Double - 8 bytes Integer/Float - 4 bytes Short - 2 bytes Byte - 1 byte

So to get the SINGLE byte that has data you can simply do: byte single = (byte) i & 0xFF If you had a bigger number up to 65535 (0xFFFF) you can do: byte b1 = (byte) ((i >> 8) & 0xFF); byte b2 = (byte) i & 0xFF If you had an even larger number in the integer range you just do b1 = i >> 24, b2 = i >> 16, etc etc etc. Subtracting 8 from the shift as that is the size of a byte.

Hope this answers your question.

OTHER TIPS

Try using Formatter, or one of its convenience wrappers like String.format e.g.:

String str = String.format("%08x", val);

This will give you a String, but I'll leave it to you to get that into a byte[]...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top