int 类型转为 二进制string
时间: 2023-12-29 20:02:53 浏览: 61
可以使用 bitset 类来将 int 类型转换为二进制字符串。例如:
```c++
#include <bitset>
#include <iostream>
int main() {
int num = 42;
std::bitset<32> binary(num);
std::cout << binary.to_string() << std::endl;
return 0;
}
```
在上面的示例中,我们使用 `std::bitset<32>` 来创建一个 32 位的二进制数,其中的 `num` 变量存储了要转换为二进制的整数。`binary.to_string()` 方法将 `bitset` 对象转换为字符串形式,输出为 "00000000000000000000000000101010"。如果要输出二进制数中的有效位数,可以使用 `binary.to_string().substr(binary.to_string().find('1'))`。
相关问题
c++ 十六进制转为二进制编程
可以使用C++中的 `bitset` 库来实现十六进制转二进制。
具体实现步骤如下:
1. 将十六进制字符串转为整型数。
2. 使用 `bitset` 将整型数转为二进制字符串。
下面是一个示例代码:
```cpp
#include <iostream>
#include <bitset>
using namespace std;
int main() {
string hexStr = "1A";
int hexNum;
sscanf(hexStr.c_str(), "%x", &hexNum); // 将十六进制字符串转为整型数
bitset<8> binaryNum(hexNum); // 将整型数转为二进制字符串
cout << binaryNum << endl; // 输出二进制字符串
return 0;
}
```
输出结果为:`00011010`
其中,`bitset<8>` 表示创建一个长度为8的二进制数。如果需要转换更长的十六进制数,需要相应地调整 `bitset` 的长度。
java将字符串转为二进制类型
可以使用 Java 中的 `getBytes()` 方法将字符串转换为字节数组,然后再将字节数组转换为二进制字符串。示例代码如下:
```java
String str = "hello world";
byte[] bytes = str.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes) {
int val = b;
for (int i = 0; i < 8; i++) {
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
}
System.out.println(binary.toString());
```
输出结果为:
```
0110100001100101011011000110110001101111001000000111011101101111011100100110110001100100
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)