This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,
visit the help center.
Closed 7 years ago.
I have 2 chars: HIGH and LOW and I'd like to convert them to an int corresponding to HIGH + the 2 left bits from LOW.
I tried somethine like :
unsigned char high;
unsigned char low;
high = 128; // 10000000
low= 128; // 10000000
int result; (should be high 10000000 + 2 left bites of low 10 = 1000000010)
// To do
return result;
Edited for more clarity.
The solution I chosed is:
return high*4 + (low >> (CHAR_BIT - 2));
You declare HIGH
and LOW
as char*
, but you don't use them as pointer. The following code works fine (BTW, avoid upper case identifiers when you don't use constants):
char high = 125;
char low = 12;
This is how I understand your question (it could be more understandable):
#include <limits.h>
int result = high + (low >> (CHAR_BIT - 2));
I have 2 chars, HIGH and LOW, and I'd like to convert them to an int
corresponding to HIGH + the 2 left bits from LOW.
Your specification is not clear. Given:
unsigned char HIGH = 152;
unsigned char LOW = 12;
It could mean:
int result = HIGH + (LOW >> 6); // Assuming CHAR_BIT == 8
Or it could mean:
int result = HIGH + (LOW & 0xC0);
Or it could mean:
int result = (HIGH << 2) | (LOW >> 6);
Or it could have some other meaning. For the values shown in the question, the first two expressions produce the same answer.
To get a more meaningful answer, you'll have to spell out the requirements much more carefully. Your actual code bears almost no discernible relationship to the requirement you specify. You have two char *
variables; you initialize them to what are almost certainly invalid addresses; you don't initialize result
. Your computations are, at best, odd.