c - Converting binary stored in 2 unsigned character to integer -
if have 2 variables:
unsigned char var1, var2; var1 = 4a; // simplicity showing hex value 4a, 1 // byte of binary representing value 4a - 0100 1010 var2 = 3f;
i want return function integer result given by: 3f4a
in c this?
int result; var2 << 8; // left shift var2 8 bits result = var1 + var2; return result;
can "cast" binary stored in char variables int in manner? i.e result return integer 16202?
although on platforms work use signed arithmetic, pedantically formally correct should use unsigned types computation of bit pattern.
now, first of all
var2 << 8;
does not left shift var2
: it's expression computing result, that's discarded.
that result of signed type int
, because int
highest common type of operands.
you want unsigned
computation, make sure @ least 1 operand of unsigned type, i.e.
return static_cast<int>( var1 + (var2 << 8u) );
to entirely bit-level-ish, replace +
bitlevel or, |
. not matter logically, , same machine code generated.
Comments
Post a Comment