gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:19:27 25 4
gpt4 key购买 nike

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

给定以下定义:

#include <limits>

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

将有符号范围 [MIN(T), MAX(T)] 映射到无符号范围 [0, MAX(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 ]

关于c++ - 将有符号整数范围映射到无符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31203839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com