Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
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 Android Security Essentials Live Lessons this week in the Android 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]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: can we store an integer in a byte array
 
Similar Threads
Type of Array's index?
NumberFormatException in System.in.read()
Wrapper class
split text file into bytesize chunks!
Conversion ?