【问题标题】:How to convert a boolean variable to unsigned char in c++?如何在 C++ 中将布尔变量转换为无符号字符?
【发布时间】:2020-09-21 08:00:21
【问题描述】:

我想将 bool 类型的变量转换为 unsigned char 变量,我尝试了以下代码,但它不起作用。

enter image description here

【问题讨论】:

  • 包含有问题的代码。避免使用链接或图片作为代码。

标签: c++11 types type-conversion


【解决方案1】:

这样的事情怎么样?

#include <iostream>
using namespace std;
main() {
   bool my_bool;
   my_bool = true;
   cout << "The int equivalent of my_bool is: " << (unsigned char)(my_bool) << endl;
   my_bool = false;
   cout << "The int equivalent of my_bool is: " << (unsigned char)(my_bool);
}

【讨论】:

  • 更像是分配给 unsigned char 变量的 bool 变量的转换,像这样: bool a = true; unsigned char B = static_cast(a);
  • 有了这个我知道B的值现在是'1',如果a的值是假的,我希望B的值是'0',相当于无符号字符布尔类型
  • 所以你不在乎它是签名还是未签名。你想要 char "0" 和 char "1" 所以只需从我的代码中删除 "unsigned" 就可以了。
猜你喜欢
  • 1970-01-01
  • 2016-05-09
  • 2015-09-29
  • 2018-09-10
  • 1970-01-01
  • 2014-05-11
  • 2012-05-20
  • 2015-12-28
  • 1970-01-01
相关资源
最近更新 更多