另一个BCD byte []到int并再次返回

时间:2012-05-10 13:38:15

标签: c# encoding bcd

我遇到了一些转换问题,并且无法找到代码中的错误, 或者想知道它必须做什么。

我有以下字节[]

byte[] bytes = {0xFF, 0xFF, 0xFE};

我用这种方式转换成ulong:

ulong next = ((uint)((((0x00 << 4) | bytes[0]) << 16) | ((bytes[1] << 8) | bytes[2])));

接下来我将1添加到下一个:

next++;

然后,我想将ulong转换回字节数组。我尝试了在这里和网上找到的几种bcd算法,但我无法得到我期望的结果:

byte[] bytes = {0xFF, 0xFF, 0xFF};

insted of

{ 0x15, 0x72, 0x77, 0x16}

我得到了我尝试的大多数解决方案。

这是我使用过的算法之一:

static Byte[] CopyAsBCD(UInt32 value)
        {
            Byte[] buffer = new byte[4];
            Int32 offset = 0;
            var length = 4;
            var s = value.ToString();
            var stringIndex = s.Length - 1;
            var bufferIndex = offset + length - 1;
            var isLower = true;

            try
            {
                while (bufferIndex >= offset && stringIndex > -1)
                {

                    if (isLower)
                        buffer[bufferIndex] = Byte.Parse(s[stringIndex].ToString());
                    else
                        buffer[bufferIndex] += (Byte)(Byte.Parse(s[stringIndex].ToString()) << 4);

                    if (!isLower)
                        bufferIndex--;
                    isLower = !isLower;
                    stringIndex--;
                }

            }
            catch
            {
            }
            return buffer;
        }

我做错了什么?或者我有一个概念问题?

1 个答案:

答案 0 :(得分:2)

你能不能只使用:

//Array padded to 8 bytes, to represent a ulong
byte[] bytes = {0, 0, 0, 0, 0, 0xFF, 0xFF, 0xFE};

var longBytes = BitConverter.ToUInt64(bytes, 0);

var arrayBytes = BitConverter.GetBytes(longBytes);

注意:您可能需要反转数组,具体取决于您所在系统的Endianness(在这种情况下,您可能需要在另一侧添加填充)。

相关问题