Convert signed int of variable bit size

oliverleo

I have a number of bits (the number of bits can change) in an unsigned int (uint32_t). For example (12 bits in the example):

uint32_t a = 0xF9C;

The bits represent a signed int of that length. In this case the number in decimal should be -100. I want to store the variable in a signed variable and gets is actual value. If I just use:

int32_t b = (int32_t)a;

it will be just the value 3996, since it gets casted to (0x00000F9C) but it actually needs to be (0xFFFFFF9C)

I know one way to do it:

union test
{
    signed temp :12;
}; 
union test x;
x.temp = a;
int32_t result = (int32_t) x.temp;

now i get the correct value -100

But is there a better way to do it? My solution is not very flexbile, as I mentioned the number of bits can vary (anything between 1-64bits).

Eugene Sh.

This relies on the implementation defined behavior of sign extension when right-shifting signed negative integers. First you shift your unsigned integer all the way left until the sign bit is becoming MSB, then you cast it to signed integer and shift back:

#include <stdio.h>
#include <stdint.h>

#define NUMBER_OF_BITS 12

int main(void) {
    uint32_t x = 0xF9C;
    int32_t y = (int32_t)(x << (32-NUMBER_OF_BITS)) >> (32-NUMBER_OF_BITS);

    printf("%d\n", y);

    return 0;
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related