c++ - Bit shifting in hexadecimal in visual studio and outputting through cout -
i trying learn c++ following tutorial online. tutorial showing me how make program using sdl2 , got lost on 1 of tutorials involving bit shifting in hex. lecturer using eclipse ide while i'm using visual studio community 2017. i'm trying "cout" output this: ff123456 using code demonstrated in tutorial.
#include <iostream> #include <string> #include <iomanip> using namespace std; int main() { //0xff123456 want resulting hexadecimal below 1 here using unsigned chars , build 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 values in color 8 bits left color += red; color <<= 8; color += blue; color <<= 8; color <<= green; cout << setfill('0') << setw(8) << hex << color << endl; return 0; } however, every time run program, cout display "0000000" instead of ff123456. there i'm doing wrong or missing here?
your color unsigned char, stands 1 byte, not four. hence, every shift <<= 8 erase assigned before. use unsigned int or, better, uint32_t-type color. further, initialize color value of alpha, , add alpha second time. suggest initialize color 0:
uint32_t color = 0; color += alpha; color <<= 8; //moves values in color 8 bits 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 color += green. and, ge ff123456 instead of ff123456, added std::uppercase.
Comments
Post a Comment