在 C++ 中将 bitset 转换为 int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19583720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:59:07  来源:igfitidea点击:

convert bitset to int in c++

c++bitset

提问by tenos

In c++. I initialize a bitset to -3 like:

在 C++ 中。我将一个位集初始化为 -3,例如:

std::bitset<32> mybit(-3);

Is there a grace way that convert mybitto -3. Beacause bitset object only have methods like to_ulongand to_string.

是否有一种优雅的方式可以转换mybit-3. 东阳位集合对象只能有类似的方法to_ulongto_string

回答by Barmar

Use to_ulongto convert it to unsigned long, then an ordinary cast to convert it to int.

使用to_ulong将其转换为unsigned long,然后使用普通强制转换将其转换为int

int mybit_int;

mybit_int = (int)(mybit.to_ulong());

DEMO

演示