0

I'm trying to read an int (32 bits) to a bytebuffer object.

I've used the method "Bytebuffer.allocate(4)", and I wish to take every 8 bits(1 byte) of the given int, into the bytebuffer object.

How can I do this?

(I need to use it in order to convert every Byte(8 bits) to a number between 0-255)

Edit: I'm just trying to get the 32 bit of an int(it's for a school project and the assignment said specifcly "we will use int not as a number, but as a binary sequence of 32 bits" and that's what I'm trying to do but with absolutely no success.

Thanks.

Aycan Yaşıt
  • 2,106
  • 4
  • 34
  • 40
Tzur
  • 3
  • 2
  • 2
    Does [this question](http://stackoverflow.com/questions/2183240/java-integer-to-byte-array) help? – Ray Toal Nov 29 '13 at 23:29
  • What do you want to do with the bits? Integer.toBinaryString(int) for example converts an int to a binary String of zeroes and ones. – isnot2bad Nov 29 '13 at 23:51

1 Answers1

-1

Use simple shift and mask operations:

byte b1 = n & 0xFf;
byte b2 = (n >> 8) & 0xFF;
byte b3 = (n >> 16) & 0xFF;
byte b4 = (n >> 24) & 0xFF;
isnot2bad
  • 24,105
  • 2
  • 29
  • 50