char and unsigned char
AFAIK, whether char is signed or not is implementation defined. Whatever it be, char is signed to me.
When you read stuff from a file, most of the time you need your chars to be unsigned (for example to read values spread over multiple bytes and store it in an int). But the file loading functions of C++ can only work with chars, not with unsigned ones, appearantly it isn't able to convert the 8 bits to another thing of 8 bits :roll:.
Anyway, how do you overcome this? Where do you do the conversion from char to unsigned char, if anywhere?
Where do you get the impression that the file loading functions only work with chars? According to MSDN, fread takes a void* buffer and fills it in. Obviously you can then cast this to whatever you want. Or are you talking about using iostreams? Even if you are, I'd assume you can get the buffer and cast it accordingly. At the end of the day, it just a bunch of bytes =)
-John
-John
Who cares wether it wants a buffer of chars or unsigned chars? It's going to treat it as a buffer of bytes anyway.
Furthermore, file streams work with any type at all, with none of that buffer crap.
Furthermore, file streams work with any type at all, with none of that buffer crap.
Besides, if you're relying on a signed/unsigned char, then you should specify it.
rather than:
use
or
rather than:
char a;
use
signed char a;
or
unsigned char a;
A signed char and an unsigned char are equivalent in terms of size and usage of bits. The only difference is when it comes to operations where negativity needs to be taken into account, such as multiplication. So, when you read a char in from getch(), you can cast it however you want.
About the only caveat is that getch returns an int if I'm not mistaken. So, do it this way:
unsigned char x;x = (unsigned char) getch();
About the only caveat is that getch returns an int if I'm not mistaken. So, do it this way:
int y;
unsigned char x;
y = getch();
if ( (y<0) || (y>255) )
{
HandleError();
x = 0;
}
else
{
x = (unsigned char) (y&0xff);
}
Quote:Original post by Inmate2993
A signed char and an unsigned char are equivalent in terms of size and usage of bits. The only difference is when it comes to operations where negativity needs to be taken into account, such as multiplication. So, when you read a char in from getch(), you can cast it however you want.unsigned char x;x = (unsigned char) getch();
About the only caveat is that getch returns an int if I'm not mistaken. So, do it this way:int y;unsigned char x;y = getch();if ( (y<0) || (y>255) ){ HandleError(); x = 0;}else { x = (unsigned char) (y&0xff);}
That's the C way of doing things. With C plus plus, you should try and use the new cast operators.
EDIT: The parser ate my plus plus
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement