Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

converting between bytes and ints

Status
Not open for further replies.

RichieMac

Programmer
Aug 18, 2004
61
GB
Hello all,

could someone tell me if it's possible to convert bytes read from a filestream into int values to carry out some processing, then to convert back into bytes to read back to a file. What I have at the moment is a .txt file that I'm reading using FileInputStream. The data, which is read into a byte array, needs to be processed using an encoding algorithm i have built. My obvious problem is that data is read in in bytes but my algorithm requires integer values for processing. Rather than change the whole encoding prog I was hoping it wouldn't be too difficult to convert the bytes into ints - and vice versa. Is this an easy task or will I have to change the encoding/decoding prog.
 
You could do something a bit like :

Code:
byte[] buf ... // your byte array read from the file
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(buf));
// read a single int from the stream
int i = dis.readInt();

This way, you leave your original byte data intact, but have an in-memory stream to read ints from.

Or you could just cast the bytes to ints as your iterate through the byte array.



--------------------------------------------------
Free Database Connection Pooling Software
 
Thanks sedj. Can you just clear up for me whether i will lose data when converting back to bytes from ints. My understanding is that ints are four bytes so what will happen to remaining three bytes if I convert from int.
 
I would not convert from ints to bytes, because you will lose precision/data.

If you use a DataOutputStream, you can use the writeInt() method.

--------------------------------------------------
Free Database Connection Pooling Software
 
Code:
42
0
999
Save as Text.
a) It's easy to parse and read.
b) It's readable with every editor.
c) It doesn't depend on the number of bytes a language uses to store ints.
d) It can be searched from the commandline:
Code:
grep 42 data.file

seeking a job as java-programmer in Berlin:
 
Ah. See what you mean now. Will try that way - it may solve my problem.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top