0

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
4

4 回答 4

1

似乎 hexdump 以其默认值将您的文件输出为两个字节块,并将它们反转。

尝试使用

hexdump -C /tmp/temp_session_TGAyUSfICJgY.txt

或者

xxd /tmp/temp_session_TGAyUSfICJgY.txt

查看按它们在文件中出现的顺序显示的字节。

于 2013-07-16T18:47:41.407 回答
0

使用 hexdump 的这个变体:

hexdump -C /tmp/temp_session_TGAyUSfICJgY.txt

您将按照 Java 程序生成的相同顺序查看字节。

我认为,默认情况下hexdump会使用 big-endian 短裤。

于 2013-07-16T18:45:00.337 回答
0

您确实需要知道写入文件的内容(以及如何写入)以确定您是否正确读取它。一旦知道文件的写入方式,您就可以控制 ByteOrder。看到这个问题。在 Java 中将 ByteBuffer 导出为 Little Endian 文件

于 2013-07-16T19:00:39.680 回答
0

尝试使用:

int read(byte[] b) 从输入流中读取一些字节并将它们存储到缓冲区数组 b 中。

而不是 int read()

于 2013-07-16T19:07:13.237 回答