-1

I am currently trying to learn c++ by following a tutorial online. This tutorial is showing me how to make a program using SDL2 and I got lost on one of the tutorials involving bit shifting in hex. The lecturer is using the Eclipse IDE while I'm using Visual Studio community 2017. Basically what I'm trying to do is get "cout" to output this: FF123456 by using the code he demonstrated in the tutorial.

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

However, every time I run the program, cout will only display "0000000" instead of FF123456. Is there something I'm doing wrong or missing here?

1 Answers1

0

Your color is an unsigned char, which stands for one byte, not for four. Hence, every shift <<= 8 will actually erase anything assigned before. Use an unsigned int or, better, a uint32_t-type for color. Further, you initialize color with the value of alpha, and then you add alpha a second time. Suggest to initialize color with 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;

Output:

FF123456

BTW: fixed typo, changed color <<= green into color += green. And, to ge FF123456 instead of ff123456, I added std::uppercase.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58