File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 Murach's Java Servlets and JSP this week in the Servlets 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
NumberFormatException in System.in.read()
Wrapper class
split text file into bytesize chunks!
Conversion ?
Type of Array's index?