将无符号短字符数组转换为无符号字符数组
Converting an array of unsigned shorts, to an array of unsigned chars
我似乎不明白这里发生了什么。我有以下警告图标;
K_USHORT usaAlertIcon[16] = { 0x0000, 0x0000, 0x0180, 0x03C0, 0x03C0, 0x0660, 0x0660, 0x0E70, 0x0E70, 0x1E78, 0x3E7C, 0x3FFC, 0x7E7E, 0x7E7E, 0xFFFF, 0x0000 };
现在,我想在我的代码中使用它,它认为数组是8位数据(unsigned char);
//---------------------------------------------------------------------------
void GraphicsDriver::Stamp(DrawStamp_t *pstStamp_)
{
K_USHORT usRow;
K_USHORT usCol;
K_USHORT usShift;
K_USHORT usIndex;
DrawPoint_t stPoint;
usIndex = 0;
for (usRow = pstStamp_->usY; usRow < (pstStamp_->usY + pstStamp_->usHeight); usRow++)
{
usShift = 0x80;
for (usCol = pstStamp_->usX; usCol < (pstStamp_->usX + pstStamp_->usWidth); usCol++)
{
// If the packed bit in the bitmap is a "1", draw the color.
if (pstStamp_->pucData[usIndex] & usShift)
{
stPoint.usX = usCol;
stPoint.usY = usRow;
stPoint.uColor = pstStamp_->uColor;
DrawPixel(&stPoint);
}
// Stamps are opaque, don't fill in the BG
// Shift to the next bit in the field
usShift >>= 1;
// Rollover - next bit in the bitmap.
// This obviously works best for stamps that are multiples of 8x8
if (usShift == 0)
{
usShift = 0x80;
usIndex++;
}
}
}
}
当将数组赋值给要发送给此函数的数据结构时,我将其强制转换为;
stStamp.pucData = (K_UCHAR*)usaAlertIcon;
然而,当我这样做时,它似乎翻转了字节。它先画左半部分,然后画右半部分;所以它从中间切开图像,把左边的部分换成右边的。
作为一个完整性检查,如果我自己显式拆分数组;
K_UCHAR ucaAlertIcon[32] = { 0x00, 0x00, 0x00, 0x00, 0x01, 0x80, 0x03, 0xC0, 0x03, 0xC0, 0x06, 0x60, 0x06, 0x60, 0x0E, 0x70, 0x0E, 0x70, 0x1E, 0x78, 0x3E, 0x7C, 0x3F, 0xFC, 0x7E, 0x7E, 0x7E, 0x7E, 0xFF, 0xFF, 0x00, 0x00 };
一切正常
谁能解释一下为什么当我做类型转换时,这些字节似乎在翻转?
谁能解释一下为什么当我做类型转换时,这些字节似乎在翻转?
字节顺序。您显然是在一台小端机器上,这意味着最低地址的字节是最不重要的字节。您需要将unsigned short
的值转换为大端格式,例如htons
就是这样做的。
#include <arpa/inet.h>
uint16_t htons(uint16_t hostshort);
你当然也可以自己做,
array[i] = (array[i] << 8) | (array[i] >> 8);
相关文章:
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 按字符值访问int数组
- 错误:字符数组的初始值设定项太多
- 对字符数组中的元素执行逐位操作
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 移动二维数组中的字符
- C++ 传递二维字符数组
- 无法在 C++ 中输入字符数组
- C++ 带结构的数组字符
- 数组字符包含量超出预期
- 读取文件并添加到数组字符
- 如何在Qt中更改或替换数组字符
- 为什么编译器不在参数中传递数组字符 *arr[] 的大小?
- 井字棋数组字符错误
- 分割数组字符