bit shifting signed integer

95 views Asked by At

I am bit shifting a sign integer first byte is exponent next 4 are mantissa. This does not always seem to work I beleive it is due to calling it a char but when i make it a signed or unisgned char it still is not 100%. any ideas?

 char mdentrypxexp[1];    
 memcpy( mdentrypxexp, message + pos, 1 );
 int32_t MDEntryPxExp = mdentrypxexp[0]; 
 std::cout <<  "MDEntryPxExp  " << MDEntryPxExp << std::endl;
 pos+=1;

 char mdentrypxmantissa[4];    
 memcpy( mdentrypxmantissa, message + pos, 4 );

 int32_t MDEntryPxMantissa = mdentrypxmantissa[0] | ( (int32_t)mdentrypxmantissa[1] << 8 ) | (int32_t)mdentrypxmantissa[2] << 16 ) | ( (int32_t)mdentrypxmantissa[3] << 24 ); 
 std::cout << "MDEntryPxMantissa  " << MDEntryPxMantissa << std::endl;
 pos+=4;

 double MDEntryPx = MDEntryPxMantissa * pow10(MDEntryPxExp);
 std::cout << " MDEntryPx=" << MDEntryPx; 
1

There are 1 answers

0
George Houpis On BEST ANSWER

You are building a signed int32_t from 4 signed int32_t. Upcasting 2's complement signed integers makes bitwise operations tricky. Use unsigned integers and then convert.

uint32_t MDEntryPxMantissa_tmp = ( static_cast< uint32_t >( mdentrypxmantissa[0] ) | ( static_cast< uint32_t >( mdentrypxmantissa[1] ) << 8 ) | static_cast< uint32_t >( mdentrypxmantissa[2] ) << 16 ) | ( static_cast< uint32_t >( mdentrypxmantissa[3] ) << 24 ) ); 
int32_t MDEntryPxMantissa = *reinterpret_cast< int32_t * >( &MDEntryPxMantissa_tmp );