将非数字字符串存储为二进制整数

Store a non numeric string as binary integer

本文关键字:二进制 整数 存储 字符串 数字 数字字符      更新时间:2023-10-16

如何转换这样的字符串

string a = "hello"; 

到它的位表示形式,存储在一个 int 中

int b = 0110100001100101011011000110110001101111

在这里ab等价的。

您不能将长字符序列(例如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;
}

此链接中的更多信息: 如何将字符转换为二进制?