将有符号整数范围映射到无符号

Mapping signed integer ranges to unsigned

我遇到一个问题,应该将有符号整数转换为无符号整数,同时保留它们的范围和顺序。

给定以下定义:

#include <limits>

#define MIN(X) std::numeric_limits<X>::min();
#define MAX(X) std::numeric_limits<X>::max();

将有符号范围 [MIN(T), MAX(T)] 映射到无符号范围 [0,最大(U)]?

其中:

T is a signed integer type

U is an unsigned integer type

sizeof(T) == sizeof(U)

我尝试了各种位运算和数值方法来想出一个解决方案,但没有成功。

unsigned int signedToUnsigned(signed int s) {
  unsigned int u =  1U + std::numeric_limits<int>::max();
  u += s;
  return u;
}

Live example here

这会将 signed_max + 1 添加到 signed int 以确保 [MIN(int), MAX(int)] 映射到 [0, MAX(unsigned int)]


为什么这个答案有效并正确映射:

当您将有符号整数与无符号整数相加时,有符号整数将提升为无符号类型。来自第 4.7 节 [conv.integral]

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). —end note ]