• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Quick Java Question

clamum

Lifer
I have a question that I think isn't very difficult to do but I'm not sure how to do it: I want to take an int (it will be anywhere from 100 to 3000) and convert it to an array of bytes. After that, I would like to get the int back out of the byte array.

Thanks for any help
 
bytearray[0] = (myInt & 0xff000000) >> 24;
bytearray[1] = (myInt & 0x00ff0000) >> 16;
bytearray[2] = (myInt & 0x0000ff00) >> 8;
bytearray[3] = (myInt & 0x000000ff);

^^ Didn't test it.... but should give you general idea.

& is the bit-wise AND operator. so it takes each bit of the operands and logically ANDs them together. >> is the right bit-shift operator... so after you & the integer with teh correct mask, you have to shift those bits over into the last 8 bits.

This would only work for a 32-bit integer.
 
Good call Crusty. As a side note, java guarantees its data type sizes so the above code is technically safe across all platforms. Kinda worries me, in case they ever decide to up it to 64, but it would have to be officially announced and everyone would know about it.
 
Is it only Sun that guaruntees the data type sizes? I would think that whoever writes the JRE determines their data type sizes.

int mast = 0xff000000;

for (int i = 0; i <= 32 ; i+=8) {
bytearray[i/8] = (myInt & mask) >> (24 - i);
mask >> 8;
}

That loop should work too, just substitute your integer size for 32, byte size for 8, and (int size - byte size) for 24.... i think
 
or you can just do:

byte[0] = (byte)int;
byte[1] = (byte)(int >> 8);
byte[2] = (byte)(int >> 16);
byte[3] = (byte)(int >> 24);
 
Back
Top