c# - 将整数编码为可变长度的大端字节数组

标签 c# endianness

我需要将一个整数写入字节数组,以便省略前导零并且字节以大端顺序写入。

例子:

int    original = 0x00123456;

byte[] encoded  = Encode(original);  //  == new byte[] { 0x12, 0x34, 0x56 };

int    decoded  = Decode(encoded);   //  == 0x123456

我的解码方法:

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)
{

}

最佳答案

根据 OP 的要求,这是一个没有 32 位数字循环的版本:

private static int Encode(int value, byte[] buffer, int index)
{
    byte temp;
    bool leading = true;

    temp = (value >> 24) & 0xFF;
    if (temp > 0) {
      buffer[index++] = temp;
      leading = false;
    }

    temp = (value >> 16) & 0xFF;
    if (temp > 0 || leading == false) {
      buffer[index++] = temp;
      leading = false;
    }

    temp = (value >> 8) & 0xFF;
    if (temp > 0 || leading == false) {
      buffer[index++] = temp;
      leading = false;
    }

    temp = value & 0xFF;
    buffer[index++] = temp;

    return index;
}

对 32 位数字使用循环的版本:

private static int Encode(int value, byte[] buffer, int index)
{
    int length = 0;

    for (int i = 3; i >= 0; i++) {
      byte temp = (byte)(value >> (8 * i));
      if (temp > 0 || length > 0) {
        buffer[index++] = temp;
        length++;
      }
    }

    return length;
}

请注意,如果输入仅为 0,此版本不会写入任何内容。

关于c# - 将整数编码为可变长度的大端字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3176116/

相关文章:

python - 在 struct.unpack 格式字符串中间切换字节序

c - 通过引用 32/64 位传递时 C 中的字节顺序问题

networking - 如何在主机和网络字节顺序之间转换 double?

c - fread 似乎是从右到左读取文件

c++ - 更改字节顺序的最快方法

c# - 如何使用 LINQ 生成新类型的对象

c# - Lucene.NET MoreLikeThis 例子

c# - 处理 UI 上未启动的触摸

c# - 如何在 .NET 程序集中嵌入文本文件?

c# - 类似 Gmail 的标签系统