简体   繁体   中英

8-bit to 4-bit integer conversion in C, converting signed int past -8?

How would I convert a number like -9 from 8 bit to 4 bit mathematically? What would it convert to? Can someone walk me through it? I'm trying to work it out using C. My current understanding is that signed integers only go to -8, how would a number like -9 be converted from 8 to 4 bit?

You can either clamp (aka saturate) the value to the valid output range or just mask out the MS 4 bits, which effectively gives modulo wraparound for out-of-range input values:

int8_t convert_8_to_4(int8_t x)
{
#if SATURATE          // limit input range to -8 .. +7
    x = min(x, 7);
    x = max(x, -8);
#else
    x &= 0x0f;        // mask all but LS 4 bits
#endif
    return x;
}

Note that if you're trying to reduce a full range 8 bit value to 4 bits then this can be achieved simply by dividing by 16, but obviously you lose precision when you do this:

int8_t convert_8_to_4(int8_t x)
{
    return x / 16;    // lose 4 LS bits
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM