c++ - 如何做一个真正的strtoul?不会摄入实际的字符串

标签 c++ binary hex strtol

将 ACTUAL 字符串输入到 strtuol 时出现问题。输入字符串应该是 32 位长的无符号二进制值。

显然,InputString = apple; 存在问题,但我不确定如何解决该问题。有什么想法吗?这不应该那么困难。不知道为什么我这么难过。

谢谢大家。

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
    char InputString[40];
    char *pEnd = NULL;          // Required for strtol()
    string apple = "11111111110000000000101010101000";
    //cout << "Number? ";
    //cin >> InputString;
    InputString = apple;
    unsigned long x = strtoul(InputString, &pEnd, 2);     // String to long

    cout << hex << x << endl;
    return 1;
}

最佳答案

更好的方法是避免遗留 C 函数并使用 C++ 标准函数:

string apple = "11111111110000000000101010101000";
unsigned long long x = std::stoull(apple, NULL, 2); // defined in <string>

注意:std::stoull 实际上会在内部调用 ::strtoull,但它允许您只处理 std::string 对象,而不必将其转换为 C 风格的字符串。

关于c++ - 如何做一个真正的strtoul?不会摄入实际的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19164549/

相关文章:

c++ - 从 USB 端口输出数据? ( window )

C++,2 参数类模板的部分特化 : unable to match function definition to an existing declaration

c++ - GDB 在操作 SSE2 寄存器时报告 EXC_BAD_ACCESS

python - 将数字转换为二进制字符串

c - 当二进制文件运行时,它是否将其整个二进制数据立即复制到内存中?我可以改变吗?

c++ - 在Apache Ignite中执行 “core”时,为什么要删除 “./configure”目录?

java - MappedByteBuffer 初始运行缓慢

C中字符串格式的十六进制数转换为0xFFFF格式的wchar_t类型

php - 为什么我在 php 中尝试将一个巨大的整数转换为十六进制时得到输出 0?

c++ - 将每 4 位解释为十六进制值