-1

我目前正在尝试通过在线教程学习 C++。本教程向我展示了如何使用 SDL2 制作程序,但我迷失了其中一个涉及十六进制位移的教程。当我使用 Visual Studio 社区 2017 时,讲师正在使用 Eclipse IDE。基本上我想要做的是让“cout”通过使用他在教程中演示的代码来输出:FF123456。

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

int main()
{
//0xFF123456 we want the resulting hexadecimal below to look like the one up here using the unsigned chars and build it sequentially byte after byte

unsigned char alpha = 0xFF;
unsigned char red = 0x12;
unsigned char blue = 0x34;
unsigned char green = 0x56;

unsigned char color = alpha;

color += alpha;
color <<= 8; //moves all the values in the color by 8 bits to the left 
color += red;
color <<= 8;
color += blue;
color <<= 8;
color <<= green;


cout << setfill('0') << setw(8) << hex << color << endl; 
return 0;
}

但是,每次我运行程序时,cout 只会显示“0000000”而不是 FF123456。我在这里做错了什么或遗漏了什么吗?

4

1 回答 1

0

color是一个无符号字符,它代表一个字节,而不是四个。因此,每个班次<<= 8实际上都会删除之前分配的任何内容。对 .使用unsigned intor,更好的是uint32_t- 类型colorcolor此外,您使用 的值进行初始化alpha,然后再次添加alpha。建议color初始化0

uint32_t color = 0;

color += alpha;
color <<= 8; //moves all the values in the color by 8 bits to the left
color += red;
color <<= 8;
color += blue;
color <<= 8;
color += green;

cout << setfill('0') << std::uppercase << setw(8) << hex << color << endl;

输出:

FF123456

顺便说一句:修正错字,color <<= green改为color += green. 而且,为了 geFF123456而不是ff123456,我添加了std::uppercase.

于 2017-08-20T18:40:58.077 回答