开发者

C# - How to convert 10 bytes to unsigned long

I have 10 bytes - 4 bytes of low order, 4 bytes of high order, 2 bytes of highest order - that I need to convert to an unsigned long. I've tried a couple different methods but neither of them worked:

Try #1:

var id = BitConverter.ToUInt64(buffer, 0);

Try #2:

var id = GetID(buffer, 0);

long GetID(byte[] buffer, int s开发者_StackOverflow中文版tartIndex)
        {
            var lowOrderUnitId = BitConverter.ToUInt32(buffer, startIndex);
            var highOrderUnitId = BitConverter.ToUInt32(buffer, startIndex + 4);
            var highestOrderUnitId = BitConverter.ToUInt16(buffer, startIndex + 8);
            return lowOrderUnitId + (highOrderUnitId * 100000000) + (highestOrderUnitId * 10000000000000000);
        }

Any help would be appreciated, thanks!


As the comments indicate, 10 bytes will not fit in a long (which is a 64-bit data type - 8 bytes). However, you could use a decimal (which is 128-bits wide - 16 bytes):

var lowOrderUnitId = BitConverter.ToUInt32(buffer, startIndex);
var highOrderUnitId = BitConverter.ToUInt32(buffer, startIndex + 4);
var highestOrderUnitId = BitConverter.ToUInt16(buffer, startIndex + 8);

decimal n = highestOrderUnitId;
n *= UInt32.MaxValue;
n += highOrderUnitId;
n *= UInt32.MaxValue;
n += lowOrderUnitId;

I've not actually tested this, but I think it will work...


As has been mentioned, a ulong isn't large enough to hold 10 bytes of data, it's only 8 bytes. You'd need to use a Decimal. The most efficient way (not to mention least code) would probably be to get a UInt64 out of it first, then add the high-order bits:

ushort high = BitConverter.ToUInt16(buffer, 0);
ulong low = BitConverter.ToUInt64(buffer, 2);
decimal num = (decimal)high * ulong.MaxValue + high + low;

(You need to add high a second time because otherwise you'd need to multiply by the value ulong.MaxValue + 1, and that's a lot of annoying casting and parentheses.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜