Reputation:
I am generating a random number and checking if the character contained is a certain character (i.e. 0xDB). This doesn't seem to be the correct way to do it as it seems like my if() is always false and goes to else.
How can I achieve this? Code below. Thanks!
if(buffer[randomNumber] == 0xDB)
count++;
else {
buffer[randomNumber] = 0xDB;
arrayChangeFlag++;
count++;
}
Upvotes: 2
Views: 201
Reputation: 104110
If this were my code, I'd probably re-write it like this:
count++;
if(buffer[randomNumber] != 0xDB) {
buffer[randomNumber] = 0xDB;
arrayChangeFlag++;
}
This makes it easier to see that count
is incremented no matter what, and makes it more clear that buffer[randomNumber]
will be set to 0xDB
on exit from this block.
It won't fix your underlying bug though; if you're using a plain char
, perhaps your environment uses a signed char
(as allowed by the standard), and the integer 0xDB
is going to be positive while the signed char
value represented by the byte 0xDB
is going to be negative. Try changing to unsigned char buffer[]
.
Upvotes: 0
Reputation: 168876
What is the type of buffer
?
I guess that it is either signed char
or implicitly-signed char
. The range of a signed char in most implementations is (-128,+127). 0xDB
is outside that range, so that equality test might never be true.
Try changing the type of buffer to unsigned char
, or replacing your test with:
if((unsigned char)buffer[randomNumber] == 0xDB)
or
if(buffer[randomNumber] == (char)0xDB)
Upvotes: 4