aspose 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
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Reply 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: 3829
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.<br /> <br />#:^P
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24081
    
  15

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://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: can we store an integer in a byte array
 
Similar Threads
Wrapper class
NumberFormatException in System.in.read()
split text file into bytesize chunks!
Type of Array's index?
Conversion ?