byte,char exactly 8 bits?

Started by
26 comments, last by GameDev.net 18 years ago
How can I make sure the variable i use for a byte is exactly 8 bits atm I am using a char but i get this warning warning C4309: 'default argument' : truncation of constant value at char aa = 254
----------------------------

http://djoubert.co.uk
Advertisement
unsigned char should be 8 bits on most, but not all systems.
the char is signed .. make it unsigned
The trouble here is that aa is a char, but 254 is an int, so the compiler is warning that the int is being truncated to a char. Since 254 is small enough, there won't be any real problem, but the warnings are annoying. You can just cast the 254 to a char to get rid of the warning:
char aa = (char)254;

To be safe when going back and forth between chars and ints, you should use unsigned types to prevent sign extension.
Just to re-iterate, the real problem with your code is as the Anonymous Poster said - a char will only hold values from -128 to +127, while an unsigned char will hold values from 0-255. Thus, in this instance, you should be using an unsigned char.

You should also explicitly type-cast as Date Hunt suggested.
I think the 'truncation' in the warning means: cannot store the value because it's too big. That would say that the compiler thinks the value is of type int, so I say that Dave is right.

And I read somewhere that most compilers have 'unsigned' on chars by default.
so if i do the following i will be fine

#define byte unsigned char

byte a;
a=255
----------------------------

http://djoubert.co.uk
typedef char byte;

Fixed a typo.
Sorry, that should be

typedef unsigned char byte;

ofcourse...
Quote:Original post by Pipo DeClown
And I read somewhere that most compilers have 'unsigned' on chars by default.


I wouldn't count on it though [wink]

And yeah, use a typedef - they were made for this kind of thing.

This topic is closed to new replies.

Advertisement