• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

can we store an integer in a byte array

 
zheng da
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to transform an integer to a byte array of size 4.
Can we do that?
 
ankur rathi
Ranch Hand
Posts: 3830
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int i[]={1,3,5,7};
byte b[]= new byte[i.length];

for(int j=0; j<i.length; j++) {
b[j] = (byte)i[j];
System.out.println(b[j]);//optional
}

Try , it may help you ...
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by zheng da:
I want to transform an integer to a byte array of size 4.
Can we do that?


Yes. This should do it, I think. Run the loop the other way to swap between big-endian and little-endian.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you need to do a lot of these, it may make sense to use a ByteArrayOutputStream fed by a DataOutputStream.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic