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

时间:2017-07-28 13:47:16

标签: c++ string binary

如何转换像

这样的字符串
string a = "hello"; 

到它的位表示,存储在int

int b = 0110100001100101011011000110110001101111

此处ab相同。

3 个答案:

答案 0 :(得分:0)

您不能在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;
}

答案 1 :(得分:0)

看起来像是一件愚蠢的事情,我觉得以下(未经测试的)代码应该有效。

#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;
}

答案 2 :(得分:-1)

ReceiptNumber    Quantity    Date           
1                5           2016-01-05
2                11          2017-04-03
3                12          2016-11-11
4                2           2017-09-09
5                96          2015-07-08
6                15          2016-12-12
7                24          2016-04-19
8                31          2017-01-02
9                10          2017-0404
10               18          2015-10-10
11               56          2017-06-02

此链接中的更多信息:how to convert a char to binary?

相关问题