Nick
Nick

Reputation: 11384

Is there an alternative to char for storing one byte numeric values?

A char stores a numeric value from 0 to 255. But there seems to also be an implication that this type should be printed as a letter rather than a number by default.

This code produces 22:

int Bits = 0xE250;
signed int Test = ((Bits & 0x3F00) >> 8);
std::cout << "Test: " << Test <<std::endl; // 22

But I don't need Test to be 4 bytes long. One byte is enough. But if I do this:

int Bits = 0xE250;
signed char Test = ((Bits & 0x3F00) >> 8);
std::cout << "Test: " << Test <<std::endl; // "

I get " (a double quote symbol). Because char doesn't just make it an 8 bit variable, it also says, "this number represents a character".

Is there some way to specify a variable that is 8 bits long, like char, but also says, "this is meant as a number"?

I know I can cast or convert char, but I'd like to just use a number type to begin with. It there a better choice? Is it better to use short int even though it's twice the size needed?

Upvotes: 0

Views: 113

Answers (1)

Ali
Ali

Reputation: 421

cast your character variable to int before printing

signed char Test = ((Bits & 0x3F00) >> 8);
std::cout << "Test: " <<(int) Test <<std::endl; 

Upvotes: 1

Related Questions