Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the standard compliant way to convert a signed integral value to a sortable, unsigned in C++?

Tags:

People also ask

How do you convert a signed integer to an unsigned integer?

To convert a signed integer to an unsigned integer, or to convert an unsigned integer to a signed integer you need only use a cast. For example: int a = 6; unsigned int b; int c; b = (unsigned int)a; c = (int)b; Actually in many cases you can dispense with the cast.

Can signed and unsigned integers store the same number of values?

Both can store 256 different values, but signed integers use half of their range for negative numbers, whereas unsigned integers can store positive numbers that are twice as large.

What is signed integer and unsigned integer in python?

A signed integer is a 32-bit integer in the range of -(2^31) = -2147483648 to (2^31) – 1=2147483647 which contains positive or negative numbers. It is represented in two's complement notation. An unsigned integer is a 32-bit non-negative integer(0 or positive numbers) in the range of 0 to 2^32-1.

Are integers signed or unsigned by default?

An int is signed by default, meaning it can represent both positive and negative values. An unsigned is an integer that can never be negative.


I have a use case where I need to convert signed values to unsigned, to make values sortable. I need this for char, short, int, long, and long long

By sortable, I mean that for signed type X, if (a < b) then converting to unsigned the converted(a) < converted(b). Note that in many cases, converting from a negative signed value directly to a unsigned value will make the value greater than 0 and breaks this constraint (two's complement implementations)

The simplest idea for a char is:

unsigned char convert(char x) {        return (unsigned char)(x ^ 0x80);  // flip sign to make it sortable } 

But this seems to be undefined behavior.

While it might be possible to convert to a larger type, add the types MIN value, and convert to the unsigned type, I'm not sure this is any more compliant, and won't work with long long

How can this be done without any undefined behavior for all types?

It seems safe to convert using memcpy, but it's not clear how to maintain sort order in a compliant way.

(Note that this is similar to: No compliant way to convert signed/unsigned of same size except I need the results to be maintain sort order)