Originally Posted by
cyberfish
Is there a way to store the absolute value of a signed value into an unsigned type of the same size?...
For example, this doesn't work because 128 would overflow int8_t...
Yep, use stdlib.h abs() function:
Code:
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
int main( void )
{
int8_t x = -128;
uint8_t y;
// since uint8_t has more precision (8 bits) than int8_t (7 bits), this is safe:
y = abs(x);
printf( "abs(%hhd) == %hhu\n", x, y );
// this will overflow!
x = abs(y);
printf( "abs(%hhu) == %hhd\n", y, x );
}
$ cc -o test test.c
$ ./test
abs(-128) == 128
abs(128) == -128
If your type has precision bigger than 31 bits (int) use labs() (long) or llabs() (long long).