Reputation: 403
Ok so I have a file that contains exactly 8 bytes:
hexdump /tmp/temp_session_TGAyUSfICJgY.txt
0000000 b21b 113c bf3a 4a92
0000008
When I cat the file I see gobbly-gook which is normal and expected (you might see real characters depending on your encoding)
cat /tmp/temp_session_TGAyUSfICJgY.txt
�<:��J
Now in java when I try to read the bytes, they come out backwards. My code is as follows:
InputStream input = new FileInputStream(session_file_param);
int a = 0;
int i=0;
while(a != -1) {
a = input.read();
System.out.println(a);
if(a != -1) {
pw[i] = (byte)a;
}
i++;
}
System.out.println("String representation of session pw is " + pw.toString());
My output is (added the =HEX for readability):
27 = 1b
178 = b2
60 = 3c
17 = 11
58 = 3a
191 = bf
146 =92
74 = 4a
-1
String representation of pw is [B@7f971afc
If I am reading a file RAW, byte by byte, shouldn't the bytes come out in order? Basically each two byte block is flipped.
EDIT:
You are right, sorry for the alarm. I made the following to test:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp = fopen("/tmp/temp_session_TGAyUSfICJgY.txt", "r");
char byte;
while (!feof(fp)) {
fread(&byte,1,1, fp);
printf("%x\n", byte);
}
}
and output:
1b
ffffffb2
3c
11
3a
ffffffbf
ffffff92
4a
Upvotes: 0
Views: 1549
Reputation: 577
Try using:
int read(byte[] b) Reads some number of bytes from the input stream and stores them into the buffer array b.
instead of int read()
Upvotes: 0
Reputation: 792
You really need to know what was written to the file (and how) to determine if you are reading it correctly. You can control the ByteOrder once you know how the file was written. See this question. Export ByteBuffer as Little Endian File in Java
Upvotes: 0
Reputation: 1384
It appears that hexdump, with its defaults, is outputting your file in two byte chunks, reversing them.
Try using
hexdump -C /tmp/temp_session_TGAyUSfICJgY.txt
or
xxd /tmp/temp_session_TGAyUSfICJgY.txt
to see the bytes displayed in the order they appear in the file.
Upvotes: 1
Reputation: 45576
Use this variant of hexdump:
hexdump -C /tmp/temp_session_TGAyUSfICJgY.txt
You will see the bytes in the same order that your Java program is producing.
I think, by default the hexdump
does big-endian shorts.
Upvotes: 0