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

IT said...

Java Training Institutes Java Training Institutes
Java Spring Hibernate Training Institutes in Chennai J2EE Training Institutes in Chennai J2EE Training Institutes in Chennai Core Java Training Institutes in Chennai Core Java Training Institutes in Chennai

navya said...

Great Article
C# Training in Chennai | C# Online Training | ASP.NET Training in Chennai

C# Training in Chennai | Dot Net Training in Chennai | Dot Net Training in Chennai

Nannie Co Pam said...

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