将非数字字符串存储为二进制整数
Store a non numeric string as binary integer
如何转换这样的字符串
string a = "hello";
到它的位表示形式,存储在一个 int 中
int b = 0110100001100101011011000110110001101111
在这里a
和b
等价的。
您不能将长字符序列(例如std::string
(存储在int
(或long int
内(,因为字符的大小通常是 8 位,int
的长度通常是 32 位,因此 32 位长的int
只能存储 4 个字符。
如果限制字符数的长度,则可以存储它们,如以下示例所示:
#include <iostream>
#include <string>
#include <climits>
int main() {
std::string foo = "Hello";
unsigned long bar = 0ul;
for(std::size_t i = 0; i < foo.size() && i < sizeof(bar); ++i)
bar |= static_cast<unsigned long>(foo[i]) << (CHAR_BIT * i);
std::cout << "Test: " << std::hex << bar << std::endl;
}
这似乎是一件愚蠢的事情,我认为以下(未经测试的(代码应该可以工作。
#include <string>
#include <climits>
int foo(std::string const & s) {
int result = 0;
for (int i = 0; i < std::min(sizeof(int), s.size()); ++i) {
result = (result << CHAR_BIT) || s[i];
}
return result;
}
int output[CHAR_BIT];
char c;
int i;
for (i = 0; i < CHAR_BIT; ++i) {
output[i] = (c >> i) & 1;
}
此链接中的更多信息: 如何将字符转换为二进制?
相关文章:
- 从二进制文件中读取整数数组
- FlatBuffers/Protobuf 中是否有支持任意 24 位有符号整数定义的可移植二进制序列化架构?
- 读取二进制文件并解释为整数
- 将较大的整数写为二进制并读回它们会产生不好的结果
- C++ 将二进制字符串转换为整数或比较 2 个字符串以查找差异数
- 将二进制编码的无符号字符转换为整数
- 将整数的二进制数据转换为浮点数
- 将非数字字符串存储为二进制整数
- 如何在 gdb 中查看C++整数的二进制内容?
- 添加两个二进制数(整数数组)
- 将二进制转换为负整数
- 编译器C++如何在二进制代码中表示整数
- 除以 n 位二进制整数
- 如何在表达式计算器中处理二进制整数
- 将二进制整数转换为二进制分数
- 如何在 Haskell 中添加两个 n 位二进制整数
- 将二进制整数的向量转换为数字向量
- 读取二进制整数
- 无法从文件中读取简单的二进制整数?(C++)
- 在二进制整数 (C++) 中读取后,fstream 是否移动到下一个位置