3

I am facing a following problem: When trying to do cast to an unsigned char I get unexpected values. The code that I am using:

unsigned char MyVal1  = ((0xF1E3 && 0xff00) >> 8);
unsigned char MyVal2 = (unsigned char)((0xF1E3 && 0xff00) >> 8);
unsigned char MyVal3 = (unsigned char)((0xF1E3 && 0xff));

I am storing all three variables in an array.

The output I am getting (looking at the values in array; array is unsigned char array):

0x00 
0x00
0x01

while I was expecting:

0xF1 
0xF1
0xE3

Could someone be kind to help me out in what am I doing wrong?

2 Answers 2

12

Operators && and & do not work the same on integers. Your operands are first converted to bool (zero/nonzero) and then anded together.

Sign up to request clarification or add additional context in comments.

1 Comment

Checkmate.... It has been a long day and I totally forgot that I was not using bitwise operator.... Much appreciated.....
10

&& is the boolean and operator; it gives 1 if both its operands are non-zero and 0 otherwise. You want the bitwise and operator, &, which gives 1 or 0 in each bit of its operands.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.