Possible Duplicate:
Java integer to byte array
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! :)
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]};
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().
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]);
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.