writing bytes (int val 0-255) to file

C

chuck

Hello,

I am trying to write integer values, 0 - 255 to a file and am having problems.

I am having problems writing any value greater than 127 (out of ascii
range), i get random values.

the full test code is here
http://pastebin.ca/743174

ok, now what i am trying to do
I break up a java long variable into 4 bytes. so first i convert the
value to a binary string with left padded 0s. (i will just show the
first byte)
Writer outfile = new FileWriter("testOutput");

String encryptedString = padString(Long.toBinaryString(value), -32, "0");
String bs0 = encryptedString.substring(0, 7+1);
int eByte0 = Integer.parseInt( bs0, 2);
outfile.write( eByte0 );

here is an example
5955599
00000000010110101110000000001111
00000000 01011010 11100000 00001111
0 90 224 15

expected value in hex editor
00 5a e0 0f

actual value value in hex editor
00 5A 88 0F

Any help is appreciated.
Chuck
 
G

Gordon Beaton

Writer outfile = new FileWriter("testOutput"); [...]
outfile.write( eByte0 );

here is an example
5955599
00000000010110101110000000001111
00000000 01011010 11100000 00001111
0 90 224 15

expected value in hex editor
00 5a e0 0f

actual value value in hex editor
00 5A 88 0F

Any help is appreciated.

A FileWriter is for writing *text*.

Use an OutputStream (e.g. a FileOutputStream) to write binary data
such as raw bytes.

/gordon

--
 
L

Lew

Roedy said:
See http://mindprod.com/jgloss/unsigned.html

bytes are -127..+127.
Also,
String encryptedString = padString(Long.toBinaryString(value), -32, "0");
String bs0 = encryptedString.substring(0, 7+1);
int eByte0 = Integer.parseInt( bs0, 2);


Let's say value is 33L. Long.toBinaryString() of that returns "100001".
You failed to show us padString(), but we'll assume that the result of that
operation is
"0000000000000000000000100001" (not long enough to represent a Long, BTW).

Now you parseInt() that String in base 2, which should yield the int value
corresponding to the binary string, which is the original value of 'value'
if the latter is within the int range, an error if it's not.

Despite the name, eByte0 is an int.

So if value is, say, 1023, then eByte0 when it's done will be 1023.

will then write the string "1023" to the file.

You might as well have just said, "outfile.write( value )". That at least
would handle the long values larger than Integer.MAX_VALUE.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,276
Latest member
Sawatmakal

Latest Threads

Top