简体   繁体   English

BitConverter.ToInt16向Number添加0xFFFF? (C#)

[英]BitConverter.ToInt16 Adds 0xFFFF to Number? (C#)

I've got a problem here that's probably something that I'm just overlooking, but I can't understand why it's happening... 我在这里遇到了一个问题,可能是我只是忽略了一些问题,但我无法理解为什么会发生这种情况......

The problem I'm having is that I'm using the bit converter to give me an Int16 from a 2-byte array, but for some reason whenever I do this -- I get the number I should get, with 0xFFFF added to the beginning of the number. 我遇到的问题是我正在使用位转换器从2字节数组中给我一个Int16,但是由于某种原因,每当我这样做时,我都会得到应该得到的数字,并在其中添加了0xFFFF数字的开头。

Example... 例...

byte[] ourArray = { 0x88, 0xA3, 0x67, 0x3D };
Int16 CreationDate = BitConverter.ToInt16(new byte[] {ourArray[2], ourArray[3]} , 0);
Int16 CreationTime = BitConverter.ToInt16(new byte[] {ourArray[0], ourArray[1]}, 0);

That will return with "CreationDate" being 0x3d67 (correct), but CreationTime being 0xffffa388. 它将以“ CreationDate”为0x3d67(正确)返回,但CreationTime为0xffffa388。

Would anyone happen to know why this is happening, and a way to correct this? 会有人碰巧知道为什么会这样,以及纠正这种情况的方法吗?

0xA388 is a negative Int16, so converted to Int32 will give a sign extended negative int with similar value. 0xA388是负Int16,因此转换为Int32将给出具有相似值的符号扩展负int。 That 0xFFFF you see is the sign extension (padding with '1' bits). 你看到的0xFFFF是符号扩展(用'1'位填充)。 Better use UInt16 and UInt32. 更好地使用UInt16和UInt32。

0xffffa388 is not an Int16. 0xffffa388不是Int16。 Are you sure you're not casting it to some 32-bit type? 您确定不将其转换为某些32位类型吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM