c++ - 将无符号短裤数组转换为无符号字符数组

标签 c++ c arrays casting

我似乎无法弄清楚这里发生了什么。我有以下警告图标;

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 };

一切都按预期工作。

有人可以解释为什么在我进行类型转换时这些字节似乎在翻转吗?

最佳答案

Can someone explain why these bytes seem to be flipping when I do a type cast?

字节顺序。您显然在一台小端机器上,这意味着最低地址的字节是最低有效字节。您需要将 unsigned short 值转换为大端格式,例如 htons 就是这样做的。

#include <arpa/inet.h>

uint16_t htons(uint16_t hostshort);

当然你也可以自己做,

array[i] = (array[i] << 8) | (array[i] >> 8);

关于c++ - 将无符号短裤数组转换为无符号字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14150166/

相关文章:

javascript - 为什么我的函数在工作和 JavaScript 之间交替

PHP 数组作为单独的行插入到 MySQL 表中

arrays - 使用 Tensorflow 中的索引对张量进行切片

java - 如何从 C++ 启动一个 java 进程,并获取它使用的内存?

c++ - 使用 unsigned char 和 string 作为函数声明

c++ - C++ 对象构造函数中的 Openmp 使用

c - QNX Neutrino 的 libpcap 库在哪里?

c++ - C++/C 中以太网 ip 中的 eth_dr 是什么?

c - 如何仅在 C 中更新打印输出中的值?

c - 有没有办法在C中获得模板效果?