C++ 将 UINT16 值转换为 UINT8 数组 [2]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1289251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:27:27  来源:igfitidea点击:

Converting a UINT16 value into a UINT8 array[2]

c++endianness

提问by dp.

This question is basically the second half to my other Question

这个问题基本上是我另一个问题的后半部分

How can I convert a UINT16 value, into a UINT8 * array without a loop and avoiding endian problems.

如何在没有循环的情况下将 UINT16 值转换为 UINT8 * 数组并避免字节序问题。

Basically I want to do something like this:

基本上我想做这样的事情:

UINT16 value = 0xAAFF;
UINT8 array[2] = value;

The end result of this is to store value into a UINT8 array while avoiding endian conversion.

这样做的最终结果是将值存储到 UINT8 数组中,同时避免字节序转换。

UINT8 * mArray;
memcpy(&mArray[someOffset],&array,2);

When I simply do memcpy with the UINT16 value, it converts to little-endian which ruins the output. I am trying to avoid using endian conversion functions, but think I may just be out of luck.

当我简单地使用 UINT16 值执行 memcpy 时,它会转换为会破坏输出的 little-endian。我试图避免使用字节序转换函数,但我想我可能只是运气不好。

回答by Martin B

How about

怎么样

UINT16 value = 0xAAFF;
UINT8 array[2];
array[0]=value & 0xff;
array[1]=(value >> 8);

This should deliver the same result independent of endianness.

这应该提供与字节顺序无关的相同结果。

Or, if you want to use an array initializer:

或者,如果您想使用数组初始值设定项:

UINT8 array[2]={ value & 0xff, value >> 8 };

(However, this is only possible if valueis a constant.)

(但是,这只有在value是常数时才有可能。)

回答by Christoph

There's no need for conditional compilation. You can bit-shift to get the higher and lower byte of the value:

不需要条件编译。您可以进行位移以获取值的高字节和低字节:

uint16_t value = 0xAAFF;
uint8_t hi_lo[] = { (uint8_t)(value >> 8), (uint8_t)value }; // { 0xAA, 0xFF }
uint8_t lo_hi[] = { (uint8_t)value, (uint8_t)(value >> 8) }; // { 0xFF, 0xAA }

The casts are optional.

演员表是可选的。

回答by Jonathan

Assuming that you want to have the high-order byte above the lower-order byte in the array:

假设您希望数组中的高位字节高于低位字节:

array[0] = value & 0xff;
array[1] = (value >> 8) & 0xff;

回答by Niki Yoshiuchi

union TwoBytes
{
    UINT16 u16;
    UINT8 u8[2];
};

TwoBytes Converter;
Converter.u16 = 65535;
UINT8 *array = Converter.u8;

回答by omikes

I used this thread to develop a solution that spans arrays of many sizes:

我使用这个线程开发了一个跨越多种大小数组的解决方案:

UINT32 value = 0xAAFF1188;
int size = 4;
UINT8 array[size];

int i;
for (i = 0; i < size; i++)
{
    array[i] = (value >> (8 * i)) & 0xff;
}

回答by RightFullRudder

A temporary cast to UINT16* should do it:

临时转换为 UINT16* 应该这样做:

((UINT16*)array)[0] = value;