I'm guessing this is a really basic understanding problem on my part but I am trying to set a variable as:
unsigned char randomnumber = 2^(0x03);
Now, in my head, I expect 2^3 = 8 (0x08) but the program is giving me 0x0001; I've tried manipulating it all the way down to:
unsigned char randomnumber = ((int)2)^((unsigned char)(0x03));
but all I'm getting is 0x01 rather than the previous 0x0001. I'm guessing this has to do with a fundamental misconception on how this is actually processing the data. Can anyone help me understand what it is I'm doing wrong?
Any help would be appreciated. Thanks, guys!
Now, in my head, I expect 2^3 = 8
So you head is doing conventional algebra in conventional notation. But your compiler is doing C, the programming language, not algebra. There's a difference. You need to find your C textbook and look up what the '^' operator actually does...
Ah, XOR operation. My bad. I can fix this problem using bit shifting but is there any way to do conventional math with "powers of" a given number? In case I wanted to do, say 3^3 and can't fix the problem with a shift operation?
I know there's a function in the math.h file (pow(3,3), which I could use). I was just wondering if there was an operator that would work in it's place.
I know there's a function in the math.h file (pow(3,3), which I could use).
In theory, you could. In practice, pow() is not a function you would want to use on a 8051. It's way too resource-hungry.
I was just wondering if there was an operator that would work in it's place.
No. And for good reasons, too. Exponentiation is a humungously complex and expensive operation if you want to do it well without losing precision while handling all the special cases well. Plus, if you do it in integers, it'll overflow for the vast majority of argument combinations, anyway.
Good to know. Thanks for the help!