wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes can we store an integer in a byte array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "can we store an integer in a byte array" Watch "can we store an integer in a byte array" New topic
Author

can we store an integer in a byte array

zheng da
Greenhorn

Joined: Dec 09, 2004
Posts: 4
I want to transform an integer to a byte array of size 4.
Can we do that?
ankur rathi
Ranch Hand

Joined: Oct 11, 2004
Posts: 3830
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

Joined: Oct 30, 2001
Posts: 1970
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.


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

If you need to do a lot of these, it may make sense to use a ByteArrayOutputStream fed by a DataOutputStream.



[Jess in Action][AskingGoodQuestions]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: can we store an integer in a byte array