bit operators help

so after few years of programming I decided it's time to learn bitwise operators (lol), but I'm having a troubles understanding why the following code doesn't work when "a" is char, but works perfectly when "a" is an int

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main()
{
	//11111111
	char a = (char)255;

	//00001111
	int b = a >> 4;

	//00000000
	int c = b & 16;
	cout << b << endl << c;

	cin.get();
	return 0;
}


i'm using char cuz I want to allocate only 8 bits, I don't need 32, the output is
1
2
3
-1
-1
16


when using int instead of char the output is correct
1
2
3
255
15
0
Last edited on
The char data type may be either signed or unsigned - the standard doesn't require one way or the other. Your compiler treats it as signed. Instead, specify unsigned char to guarantee that you are working with an unsigned type. Better yet, use std::uint8_t

http://en.cppreference.com/w/cpp/header/cstdint

You should always use the types from that header when the size of a type is important.
Last edited on
Topic archived. No new replies allowed.