0

いくつかの変換に問題があり、コードの何が問題なのか、またはコードが何をしなければならないのかという考えを見つけることができません。

次のバイトがあります[]

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};

の代わりに

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

私が試したほとんどのソリューションで得ています。

以下は、私が使用したアルゴリズムの 1 つです。

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;
        }

私が間違っていることは何ですか?または私は概念の問題を抱えていますか?

4

1 に答える 1

2

Can you not just use:

//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);

Note: you may need to reverse the array, depending on the Endianness of the system you're on (in which case you may need to add padding to the other side).

于 2012-05-10T13:42:27.973 に答える