Skip to main content
gamedev.net
🔒 Locked

typecast question

Started by adam17 4 replies 950+ views
Original Post
adam17
adam17
im trying to load some information from a bmp file into my program. reading the data works great. once i load the data, i scan through it trying to find certain color values. the data is of type unsigned char. when i compile the program in Dev-C++ it gives me a warning: comparison is always false due to limited range of data type im checking my values like this: if(image_data == (char)255) //checks to see if color channel is (char)255 it works fine if i check for a value of 0. any ideas? the problem is probably staring me in the face, but i just cant see it lol.
rip-off
rip-off
The compiler may implement char as signed or unsigned. If signed, with 8 bits (a common value for the number of bits in a char - though the implementation is allowed more) that means you are talking about a maximum value of 127, so the comparison can never be true.
adam17
adam17
WOW that was quick! i tried changing the type cast to (unsigned char)255. this time the error is not there, but the condition never passes.
microdot
microdot
I believe C++ distinguishes 'char', 'unsigned char', and 'signed char' as three seperate types, where it's implimentation defined whether 'char' is signed or unsigned. Either way you should be casting to the same type in any case: static_cast<unsigned char>(255).

EDIT:
Bah! Beaten to the punch.

That or use an unsigned literal: 255u;
<span class="smallfont">That is not dead which can eternal lieAnd with strange aeons even death may die.   -- "The Nameless City" - H. P. Lovecraft</span>
Antheus
Antheus
Why type-cast in the first place?

if(image_data == 255)


Or better yet:
if(image_data == 0xff)


Quote:
i tried changing the type cast to (unsigned char)255. this time the error is not there, but the condition never passes.


Also, what is the type of image_data? Is it unsigned char? If not, then the image_data may only be in -128..127 range.

An example:
typedef unsigned char byte;byte image_data[65536];if(image_data == 0xff) {}


This gives you a way to distinguish that you want a special type - char's aren't really suitable for images. It's just semantics, but still, it makes things clearer IMHO.
rip-off
rip-off
Make image_data have the type unsigned char. As mentioned by the above poster, C++ has three distinct types for char.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.