gpt4 book ai didi

c++ - 位集和有符号值

转载 作者:行者123 更新时间:2023-11-30 02:31:57 25 4
gpt4 key购买 nike

我正在使用 std::bitset将十进制值转换为其二进制表示形式,但我不确定 bitset 是否是否处理有符号值。

例如,bitset<10>(5)给你0000000101 .但是如果它是bitset<10>(-5)怎么办? ?

这是我的具体代码:

while (getline(ss, token, ',')){
ss.ignore();
myString.push_back(token);
}
myString[0].erase(0, 1);
myString[1].erase(0, 1);
rt = bitset<7>(stoi(myString[0])).to_string();
ra = bitset<7>(stoi(myString[1])).to_string();
i10 = bitset<10>(stoi(myString[2])).to_string();

i10应该签署。我当前的代码会处理带符号的值吗? myString 将保留用户输入的十进制表示形式,但我需要进行一些连接并写入文件,以便我轻松转换为字符串。

最佳答案

bitset本身不处理签名。您正在调用的构造函数采用 unsigned整数。来自 [bitset.cons]:

constexpr bitset(unsigned long long val) noexcept;

Effects: Constructs an object of class bitset<N>, initializing the first M bit positions to the corresponding bit values in val. M is the smaller of N and the number of bits in the value representation (3.9) of unsigned long long. If M < N, the remaining bit positions are initialized to zero.

所以如果你用 -5 调用它, 转换为 unsigned long long作为0xfffffffffffffffb .它的底部 10 位是 0x3fb ,这是你得到的集合。但它是未签名的。这两个转换函数都会返回一个无符号值(来自 [bitset.members]):

unsigned long to_ulong() const;
unsigned long long to_ullong() const;

所有这些都是说 - a bitset是一组位。它没有标志。第一点并不特别——只是另一点。

关于c++ - 位集和有符号值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36988411/

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