Sign in to follow this  
xrazybud

char problem (255...?)

Recommended Posts

xrazybud    122
char test[2]; test[0] = 67; test[1] = 68; That will print the values when using printf("%d %d\n", test[0], test[1]); but whenever I use a higher number it will come up with a negative number. For example, test[0] = 247; will print out a -9. I thought chars could hold up to 255. What's going on here?

Share this post


Link to post
Share on other sites
bakery2k1    712
_unsigned_ chars can hold up to 255. char may default to signed or unsigned, and it appears in your case that they are signed (in which case they will hold values from -128 to +127 inclusive).

Share this post


Link to post
Share on other sites
Replicon    306
char is a signed, 8-bit value (-128 .. 127). Try using "unsigned char" (or %u or somesuch in your printf).

EDIT: Haha and I tried to say TWO separate things to limit the chances of being beaten to it lol.

Share this post


Link to post
Share on other sites
JohnBolton    1372
char can represent numbers in the range of 0 - 255 or -128 to 127. Which one depends on the compiler. Most compilers have signed char. If you want the range to be 0-255, use unsigned char.

But as LeapingLizzard pointed out, the interpretation by printf depends on the format more than type of the variable.

Share this post


Link to post
Share on other sites
dave    2187
There are three unrelated types you should look out for here:

char
signed char
unsigned char

and all their pointers are unrelated, so you have to reinterpret_cast between them.

Dave

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
There is actually an easy fix for you; you need the /J option on the compiler (char is always unsigned). This is often desirable anyway if you want to process european characters from 128 to 255.

Oh, and the /J is only on the Microsoft compilers but I'm pretty sure any compiler worth its weight in more than feathers has such an option.

PufferFish

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this