Converting Int to bytes

Please support our Java advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Mar 2004
Posts: 10
Reputation: Meldroz is an unknown quantity at this point 
Solved Threads: 0
Meldroz Meldroz is offline Offline
Newbie Poster

Converting Int to bytes

 
0
  #1
Mar 23rd, 2005
Hey guys and gals,

an int in java is 4 bytes as we all know i bet.

Trying to break my into 4 bytes :

int foo = 87;

bytes[4] mybyte = new bytes[4];

the problem is i don't really know how to break my int into single bytes
i tried this:
bytes[0] = foo | 1 <<(7-8); //trying to get bits 0-7 here, not working.

not good with shifting, if anyone can give me a boost, it will be much appreciated.

thank you,
Mel
Reply With Quote Quick reply to this message  
Join Date: Mar 2005
Posts: 53
Reputation: aj.wh.ca is an unknown quantity at this point 
Solved Threads: 1
aj.wh.ca aj.wh.ca is offline Offline
Junior Poster in Training

Re: Converting Int to bytes

 
0
  #2
Mar 24th, 2005
Hi,

heres the way
mybyte[0] =(byte)( foo >> 24 );
mybyte[1] =(byte)( (foo << 8) >> 24 );
mybyte[2] =(byte)( (foo << 16) >> 24 );
mybyte[3] =(byte)( (foo << 24) >> 24 );

cheers,
aj.wh.ca
Reply With Quote Quick reply to this message  
Join Date: Mar 2004
Posts: 10
Reputation: Meldroz is an unknown quantity at this point 
Solved Threads: 0
Meldroz Meldroz is offline Offline
Newbie Poster

Re: Converting Int to bytes

 
0
  #3
Mar 29th, 2005
Yeah that works, even though it looks weird.:lol:
Thanks,
Mel

Originally Posted by aj.wh.ca
Hi,

heres the way
mybyte[0] =(byte)( foo >> 24 );
mybyte[1] =(byte)( (foo << 8) >> 24 );
mybyte[2] =(byte)( (foo << 16) >> 24 );
mybyte[3] =(byte)( (foo << 24) >> 24 );

cheers,
aj.wh.ca
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



Tag cloud for Java
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC