Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need fastest way to convert 2's complement to decimal in C

Tags:

c

I have a certain 18 bits (which are in 2's complement) within 32 bits. I need to convert them to decimal. Please show me a code snippet in C.

like image 523
kp11 Avatar asked Jan 23 '23 05:01

kp11


1 Answers

First you need to do sign extension on your 18 bits, to fill out the native int:

const int negative = (smallInt & (1 << 17)) != 0;
int nativeInt;

if (negative)
  nativeInt = smallInt | ~((1 << 18) - 1);
else
  nativeInt = smallInt;

If the number is considered negative (i.e. bit 17 is set), we bitwise-or it with a bit pattern that has ones in all the remaining bits. This creates the proper negative native-sized integer.

Then just print the native integer as usual, since you sound as if you need a decimal string representation:

char buf[12];

snprintf(buf, sizeof buf, "%d", nativeInt);

Of course, this last part might not at all match your expectaions; it's not perhaps "fastest". Since you have a limited input range of 18 bits, it's probably possible to come up with something a bit more optimized.

A few ideas:

  1. Remove the buffer size argument (i.e. use sprintf()) since we can be quite sure about the maximum number of characters needed.
  2. Since we know the range, use something less general that never checks for values outside the range.
  3. Use itoa() if you have it, less general than s*printf() so might be faster.
like image 146
unwind Avatar answered Feb 02 '23 15:02

unwind