gpt4 book ai didi

c# - 将 Int 转换为两个 Shorts 返回填充数据/负值

转载 作者:太空宇宙 更新时间:2023-11-03 12:20:40 25 4
gpt4 key购买 nike

我有一段简单的代码可以将一个 Int 转换为两个 short:

public static short[] IntToTwoShorts(int a)
{
byte[] bytes = BitConverter.GetBytes(a);
return new short[] { BitConverter.ToInt16(bytes, 0), BitConverter.ToInt16(bytes, 2) };
}

如果我传入 1851628330 (0x6E5D 9B2A),结果是:

{short[2]}
[0]: -25814
[1]: 28253

问题是-258140xFFFF 9B2A

我尝试过各种方式,包括位移位。这是怎么回事?该结果不是,也没有16 !

最佳答案

诀窍是在将两个 short 组合回 int 时使用 ushort:

public static short[] IntToTwoShorts(int a) {
unchecked {
return new short[] {
(short) a,
(short) (a >> 16)
};
}
}

public static int FromTwoShorts(short[] value) {
unchecked {
if (null == value)
throw new ArgumentNullException("value");
else if (value.Length == 1)
return (ushort)value[0]; // we don't want binary complement here
else if (value.Length != 2)
throw new ArgumentOutOfRangeException("value");

return (int)((value[1] << 16) | (ushort)value[0]); // ... and here
}
}

意外行为的原因是负数(如-25814)表示为binary complements所以你有相同值(-25814)在不同的整数类型中以不同的方式表示:

-25814 ==             0x9b2a // short, Int16
-25814 == 0xffff9b2a // int, Int32
-25814 == 0xffffffffffff9b2a // long, Int64

一些测试

int a = 1851628330;
short[] parts = IntToTwoShorts(a);

Console.WriteLine($"[{string.Join(", ", parts)}]");
Console.WriteLine($"{FromTwoShorts(parts)}");
Console.WriteLine($"{FromTwoShorts(new short[] { -25814 })}");
Console.WriteLine($"0x{FromTwoShorts(new short[] { -25814 }):X}");

结果:

[-25814, 28253]
1851628330
39722
0x9B2A

关于c# - 将 Int 转换为两个 Shorts 返回填充数据/负值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47454426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com