【发布时间】:2010-07-04 20:30:31
【问题描述】:
我需要将一个整数写入字节数组,以便省略前导零并且字节以大端顺序写入。
例子:
int original = 0x00123456;
byte[] encoded = Encode(original); // == new byte[] { 0x12, 0x34, 0x56 };
int decoded = Decode(encoded); // == 0x123456
我的Decode 方法:
private static int Decode(byte[] buffer, int index, int length)
{
int result = 0;
while (length > 0)
{
result = (result << 8) | buffer[index];
index++;
length--;
}
return result;
}
我正在努力想出一个 Encode 方法,该方法不需要临时缓冲区或在以小端顺序写入字节后反转字节。有人可以帮忙吗?
private static int Encode(int value, byte[] buffer, int index)
{
}
【问题讨论】:
-
为什么 Encode() 需要一个 byte[] 参数?它应该返回一个。
-
@Hans Passant:在指定索引处写入需要一个字节[]。我想避免不必要的 byte[] 分配。
-
好的,有道理。但是最终读取这个 byte[] 的代码应该如何知道它应该读取多少有效字节呢?
-
@Hans Passant:
Encode返回写入的字节数。该值沿编码整数存储,因此我可以在解码时将长度传递给Decode。
标签: c# endianness