Int to Bits conversion

Grettings,

i have an intetger var, and i'm trying to get specific bytes from them.

ex :

int foo= 67;

byte[4] b = new byte[4]; // int has 4 bytes in java

b = foo | 1 << (7-8); // should give me the first 8 bits of foo but not working, probably doing it wrong.

i'm basically trying to extract the bits 0-7, 8-15, and so on and store them in my array of byte.

Any pointers would help, i am weak when it comes to bit manipulation.
Thank you,

Mel

• The toBytes method below should do it:

[code]
public class IntToBytes {

public static byte[] toBytes(int n) {
byte[] barr = new byte[4];

for (int i = barr.length - 1; i >= 0; i--) {
barr[i] = (byte) n;
n >>= 8;
}

return barr;
}

public static void println(byte[] barr) {
for (int i = 0; i < barr.length; i++) {
print(barr[i]);
}
System.out.println();
}

public static void print(byte b) {
if ((mask & b) != 0) {
System.out.print('1');
} else {
System.out.print('0');
}
}
}

public static void main(String[] args) {
int[] tests = { 0x00000001, 0xFFFFFFFF, 0x80000000, };

for (int i = 0; i < tests.length; i++) {
System.out.print(tests[i] + " = ");
byte[] barr = toBytes(tests[i]);
println(barr);
}
}
}
[/code]

---------------------------------

• Thanks for the help, yeah i was trying to do something like this, as part of a bigger program.

thanks again,
Mel

: The toBytes method below should do it:
:
: [code]
: public class IntToBytes {
:
: public static byte[] toBytes(int n) {
: byte[] barr = new byte[4];
:
: for (int i = barr.length - 1; i >= 0; i--) {
: barr[i] = (byte) n;
: n >>= 8;
: }
:
: return barr;
: }
:
: public static void println(byte[] barr) {
: for (int i = 0; i < barr.length; i++) {
: print(barr[i]);
: }
: System.out.println();
: }
:
: public static void print(byte b) {
: while (mask > 0) {
: if ((mask & b) != 0) {
: System.out.print('1');
: } else {
: System.out.print('0');
: }
: }
: }
:
: public static void main(String[] args) {
: int[] tests = { 0x00000001, 0xFFFFFFFF, 0x80000000, };
:
: for (int i = 0; i < tests.length; i++) {
: System.out.print(tests[i] + " = ");
: byte[] barr = toBytes(tests[i]);
: println(barr);
: }
: }
: }
: [/code]
:
: ---------------------------------