在 C++ 中将 unsigned char(字节)数组转换为 unsigned Short

发布于 2024-12-06 11:27:40 字数 423 浏览 8 评论 0原文

我有 array^ byteArray ,我需要提取 Little Endian 序列中的字节以生成无符号短整型和整数。我已经尝试了以下我能想到的所有组合,因此寻求帮助。

int x = UInt32(byteArray[i]) + (UInt32)(0x00ff) * UInt32(byteArray[i + 1]);
int x = UInt32(byteArray[i]) + UInt32(0x00ff) * UInt32(byteArray[i + 1]);
int x = byteArray[i] + 0x00ff * byteArray[i + 1];

问题是最低有效字节(在 i+1 处),我知道它是 0x50,但生成的 Short/int 报告低字节为 0x0b。高字节不受影响。

我认为这是一个符号错误,但我似乎无法修复它。

I have array^ byteArray and I need to extract bytes in Little Endian sequence to make unsigned shorts and ints. I've tried every combination of the following I can think of so am asking for help.

int x = UInt32(byteArray[i]) + (UInt32)(0x00ff) * UInt32(byteArray[i + 1]);
int x = UInt32(byteArray[i]) + UInt32(0x00ff) * UInt32(byteArray[i + 1]);
int x = byteArray[i] + 0x00ff * byteArray[i + 1];

The problem is the least significant byte (at i+1) I know it is 0x50 but the generated short/int reports the lower byte as 0x0b. The higher byte is unaffected.

I figure this is a sign error but I can't seem to be able to fix it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

隔岸观火 2024-12-13 11:27:40

您正在使用托管代码。 Endian-ness 是框架了解的实现细节:

array<Byte>^ arr = gcnew array<Byte> { 1, 2, 3, 4 };
int value = BitConverter::ToInt16(arr, 1);
System::Diagnostics::Debug::Assert(value == 0x302);

框架的假设是否正确取决于数据来自何处。

You are using managed code. Endian-ness is an implementation detail that the framework is aware of:

array<Byte>^ arr = gcnew array<Byte> { 1, 2, 3, 4 };
int value = BitConverter::ToInt16(arr, 1);
System::Diagnostics::Debug::Assert(value == 0x302);

Whether the framework's assumptions are correct depends on where the data came from.

温柔少女心 2024-12-13 11:27:40

从两个 8 位整数生成 16 位整数的正确方法是 value = static_castint16_t >( hibyte ) << 8 |洛字节;

The proper way to generate an 16 bit int from two 8 bit ints is value = static_cast< int16_t >( hibyte ) << 8 | lobyte;

羅雙樹 2024-12-13 11:27:40
int y = byteArray[i] | byteArray[i + 1] << 8;

是你需要使用的。 (另请参阅将向量转换为向量)

int y = byteArray[i] | byteArray[i + 1] << 8;

is what you need to use. (see also Convert a vector<unsigned char> to vector<unsigned short>)

梦中的蝴蝶 2024-12-13 11:27:40

你想这样做

int x = UInt32(byteArray[i]) | (UInt32(byteArray[i + 1]) << 8);

你的乘数把事情搞砸了。

You want to do this instead

int x = UInt32(byteArray[i]) | (UInt32(byteArray[i + 1]) << 8);

Your multipliers are messing things up.

愛放△進行李 2024-12-13 11:27:40

您必须将第二个字节乘以 0x0100 而不是 0x00ff

就像在十进制中,你乘以十,而不是九。

You have to multiply the second byte with 0x0100 instead of 0x00ff.

It's like in the decimal system, where you multiply by ten, not by nine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文