Wednesday, March 25, 2009

java how to convert int to Byte array, and how to assign int value to Byte

Byte only have a constructor which takes Byte itself, so anything like

Byte b = new Byte(1);

or

Byte b = 1;

will all fail;

 

The easiest way to assign int to Byte is using the empty constructor, then = operator.

Byte b;

b = 1;

To convert int to Byte array, try the following:

t[0] =(Byte)( foo >> 24 );
t[1] =(Byte)( (foo << 8) >> 24 );
t[2] =(Byte)( (foo << 16) >> 24 );
t[3] =(Byte)( (foo << 24) >> 24 );

6 comments:

Dechu said...

BitConverter, hahahhaha

Dechu said...

i think it would be more clear if you do it like this:

t[0] =(Byte)( foo >> 24 & 0xFF );
t[1] =(Byte)( foo >> 16 & 0xFF );
t[2] =(Byte)( foo >> 8 & 0xFF );
t[3] =(Byte)( foo & 0xFF );

and don't forget it's endian-dependent

IT said...

Great step by step solution, thanks for the help!

Spring Hibernate Online Training | Hibernate Training in Chennai Java Training Institutes


Hibernate Online Training | Java Online Training | Java EE Online Training

Nannie Co Pam said...

Great Article
IEEE Final Year Projects for CSE
IEEE Project Centers in Chennai

james said...
This comment has been removed by the author.
james said...

Thanks for resolving my issue. I am very confused about how to convert java into a byte array and how it connects it's very helpful for me. Now After this solution I resolve my issue easily. Now its time to avail Hi Vis Traffic Jacketfor more details.