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.
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:
sprintf()
) since we can be quite sure about the maximum number of characters needed.itoa()
if you have it, less general than s*printf()
so might be faster.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With