【发布时间】:2014-12-31 18:01:18
【问题描述】:
我继承了具有以下规范的二进制文件格式:
| F | E | D | C | B | A | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0
0:| Status bit | ------ 15 - bit unsigned integer -----------
1:| Status bit | ---- uint:10 ---- | ---- uint:5 ----
Erlang 中的位匹配非常棒。所以我很想做这样的事情:
<<StatBit1:1, ValA:15/unsigned>> = <<2#1000000000101010:16>>.
<<StatBit2:1, ValB:10/unsigned, ValC:5/unsigned>> = <<2#0000001010100111:16>>.
问题是我需要处理的文件保存在 8-bit-little-endian
惯例。所以上例中文件的前 8 位将是
00101010 然后1000000 等
{ok, S} = file:open("datafile", [read, binary, raw]).
{ok, <<Byte1:8, Byte2:8, Byte3:8, Byte4:8>>} = file:read(S,4).
io:format(
" ~8.2.0B | ~8.2.0B | ~8.2.0B | ~8.2.0B ~n ",
[Byte1, Byte2, Byte3, Byte4]).
# 00101010 | 1000000 | 10100111 | 00000010
# ok
所以我求助于读取和交换字节:
<<StatBit1:1, ValA:15/unsigned>> = <<Byte2:8, Byte1:8>>.
<<StatBit2:1, ValB:10/unsigned, ValC:5/unsigned>> = <<Byte4:8, Byte3:8>>.
或者,我可以读取 16 位 little-endian,然后“解析”它:
{ok, S} = file:open("datafile", [read, binary, raw]).
{ok, <<DW1:16/little, DW2:16/little>>} = file:read(S,4).
<<StatBit1:1, ValA:15/unsigned>> = <<DW1:16>>.
<<StatBit2:1, ValB:10/unsigned, ValC:5/unsigned>> = <<DW2:16>>.
这两种解决方案都让我同样感到沮丧。我仍然怀疑有一个很好的方法 处理这种情况。有吗?
【问题讨论】:
-
只是文件的前4个字节需要处理吗?无论哪种方式,我认为您的第二种方法都很好,除了您可以将最后两行合并为
<<StatBit1:1, ValA:15/unsigned, StatBit2:1, ValB:10/unsigned, ValC:5/unsigned>> = <<DW1:16, DW2:16>>。 -
不,@SteveVinoski,这些是具有非常复杂格式的巨大文件,就像这样。当其中有 32 位时间戳时,它变得更加荒谬。在这种情况下,字节就像
<<B2,B1,B4,B3>>... -
也许您能做的最好的事情是首先对文件运行“dd if=infile of=outfile conv=swab”(当然,保留原件作为备份)。那么一切都会简单得多。您的 32 位时间戳将变为 >,一切正常。
标签: erlang endianness