Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using char for small integer (C++)

Tags:

c++

integer

char

I read that one can use "char" for small integers. However, when I try,

unsigned char A = 4;
std::cout << A << std::endl;

it gives a character, not 4.

like image 323
Shibli Avatar asked Jan 29 '12 17:01

Shibli


People also ask

Can you use char for numbers in c?

Software Engineering C C uses char type to store characters and letters. However, the char type is integer type because underneath C stores integer numbers instead of characters.In C, char values are stored in 1 byte in memory,and value range from -128 to 127 or 0 to 255.

Can you use char as an integer?

char in java is defined to be a UTF-16 character, which means it is a 2 byte value somewhere between 0 and 65535. This can be easily interpreted as an integer (the math concept, not int ). char in c is defined to be a 1 byte character somewhere between 0 and 255.

Can you cast a char to an int in c?

We can convert char to int by negating '0' (zero) character. char datatype is represented as ascii values in c programming. Ascii values are integer values if we negate the '0' character then we get the ascii of that integer digit.

Can you use char for numbers?

The CHAR data type stores any string of letters, numbers, and symbols. It can store single-byte and multibyte characters, based on the database locale.


2 Answers

What you are experiencing are the effects of operator overloading. The << operator assumes that you most likely want to print a character when you hand it a variable of type char, therefore it behaves differently than you would expect it for integral variables.

As suggested by Vivek Goel you can force the compiler to select the overload you actually want:

unsigned char A = 4;
std::cout << static_cast<unsigned int>(A) << std::endl;

Addendum: Unless you are working on an environment with severely constrained resources (esp. tiny memory), you are optimising on the wrong end. Operations on unsigned int are typically faster than on unsigned char, because your processor cannot fetch single bytes but has to get at least a multiple of 4 and mask out the other 3 bytes.

like image 147
bitmask Avatar answered Oct 13 '22 07:10

bitmask


There is an overload of operator<< for std::ostream and (signed/unsigned) char that performs character output; in order to output the integer value of the character, you need to perform a cast:

std::cout << (int)A << std::endl;

However, this is what’s called an “old-style” (more specifically C-style) cast. C++ has casting operators that are more explicit, easier to search for, and generally preferred:

std::cout << static_cast<int>(A) << std::endl;

But this is cumbersome to type; the idiomatic alternative is to use the + operator, which promotes its argument to (unsigned) int:

std::cout << +A << std::endl;

This is what you should use.

like image 36
Jon Purdy Avatar answered Oct 13 '22 07:10

Jon Purdy