现在我有一个程序,我必须从二进制文件中读取数字。数字是在小端,我必须转换成为Java代码大endian。我没有得到任何东西。任何人都可以发布我怎么能做到这一点。求求你了,谢谢你。
使用nio和ByteBuffer
读取它,你将会完成.order(ByteOrder.LITTLE_ENDIAN)
。
的Javadoc
看起来像番石榴测试支持它。
自从几年以来,Appache有一个LittleEndianInputStream
目前为止我的答案很好,但是我不得不承认,现在我花在.NET上的时间比在java中花费的时间还多。
不过,我的确感觉到,除了别人在这里提出的答案之外,实际上还是值得发表一个答案来描述小端和大端之间的区别。
通常,当我看到这样的问题时,人们并没有意识到这实际上是一个非常简单的任务,只需要5分钟左右的时间来执行。
所有关于给定数字字节的顺序都是实际存储在二进制文件中的。
我们举一个简单的例子,说明一个16位的“短整数”(可以被这个影响的最小尺寸)
如果停下来以“字节”的方式来思考这个问题,那么你马上会看到16位实际上等于2个字节。
现在,如果你开始把这些字节分解成最低和最高的顺序,你实际上得到一个低位字节和一个高位字节。
如果我们想象一下,我们有511的值,也就是2个字节的值
1
和
256
为什么?
数字中的位数是2的幂,如果你从右到左穿过两个幂的位,你会得到:
128 64 32 16 8 4 2 1
如果将所有这些列添加到一起,则会看到您可以获得的最大值为255
当所有的位都满了,你必须进入下一个位,所以为了得到511,我们必须有
256 128 64 32 16 8 4 2 1
通过分割成字节的扩展真的变成了
1 | 128 64 32 16 8 4 2 1
用| 字符表示两个8位字节之间的分割。
或以图形形式
------------- | 1 | 255 | -------------
我不打算深入Binary,否则我会结束话题,但是有很多像样的维基百科参考文献:
http://en.wikipedia.org/wiki/Binary_number
回到我们的字节…
当你写这些字节到一个文件,你可以写1然后255,或者你可以写255然后1
如果你先写1,那么这就是所谓的“Big Endian”,因为你先写两个字节的最大(最高)值。
如果你先写255,那么你先写两个值中最小的(低),然后给出名字“Little Endian”
这真的很容易,如果值作为一个“小端”值存储在文件中,那么你基本上需要做到以下几点:
Read One Byte into A Read One Byte into B Make 16 bit Result = (B << 8) + A
如果它以“Big Endian”值存储在文件中
Read One Byte into A Read One Byte into B Make 16 bit Result = (A << 8) + B
其他数字类型也一样简单,采取一个常规的32位整数…
分解它等于4,8位字节
----------------- | 4 | 3 | 2 | 1 | -----------------
1是最低的,4是最高的。
在“Little Endian”中 ,字节将被存储在文件中,如下所示:
----------------- | 1 | 2 | 3 | 4 | -----------------
把它读回来:
Read One Byte into A Read One Byte into B Read One Byte into C Read One Byte into D Make 32 bit Result = (D << 24) + (C << 16) + (B << 8) + A
和“Big Endian” :
----------------- | 4 | 3 | 2 | 1 | -----------------
把它读回来:
Read One Byte into A Read One Byte into B Read One Byte into C Read One Byte into D Make 32 bit Result = (A << 24) + (B << 16) + (C << 8) + D
所以你看,只要你知道如何阅读单个字节(在任何语言),你真的不需要任何额外的例程或库调用,一点点的左移是你所需要的…
对那些好奇的人来说 :
写一个32位的整数
“小端” :
Make R = 32 bit integer to store Make 8 bit Value A = R AND 255 Make 8 bit Value B = (R >> 8) AND 255 Make 8 bit Value C = (R >> 16) AND 255 Make 8 bit Value D = (R >> 24) AND 255 Write A as byte to file Write B as byte to file Write C as byte to file Write D as byte to file
“Big Endian” :
Make R = 32 bit integer to store Make 8 bit Value A = R AND 255 Make 8 bit Value B = (R >> 8) AND 255 Make 8 bit Value C = (R >> 16) AND 255 Make 8 bit Value D = (R >> 24) AND 255 Write D as byte to file Write C as byte to file Write B as byte to file Write A as byte to file
你可能在代码中做错了什么。 我最近写了一篇关于如何读写二进制文件以及如何转换字节顺序的博文。 在读取数据到字节之后,您需要调用flip()
FileChannel fc = (FileChannel) Files.newByteChannel(Paths.get(filename), StandardOpenOption.READ); ByteBuffer byteBuffer = ByteBuffer.allocate((int)fc.size()); byteBuffer.order(ByteOrder.LITTLE_ENDIAN); fc.read(byteBuffer); byteBuffer.flip();
http://pulasthisupun.blogspot.com/2016/06/reading-and-writing-binary-files-in.html