Converting string of 1s and 0s into binary value(将 1 和 0 的字符串转换为二进制值)
问题描述
我正在尝试将来自标准输入的 1 和 0 的传入字符串转换为它们各自的二进制值(其中诸如11110111"之类的字符串将转换为 0xF7).这似乎很简单,但我不想重新发明轮子,所以我想知道 C/C++ 标准库中是否有任何东西可以执行这样的操作?
I'm trying to convert an incoming sting of 1s and 0s from stdin into their respective binary values (where a string such as "11110111" would be converted to 0xF7). This seems pretty trivial but I don't want to reinvent the wheel so I'm wondering if there's anything in the C/C++ standard libs that can already perform such an operation?
推荐答案
#include <stdio.h>
#include <stdlib.h>
int main(void) {
    char * ptr;
    long parsed = strtol("11110111", & ptr, 2);
    printf("%lX
", parsed);
    return EXIT_SUCCESS;
}
对于较大的数字,有一个 long long 版本,strtoll.
For larger numbers, there as a long long version, strtoll.
这篇关于将 1 和 0 的字符串转换为二进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 1 和 0 的字符串转换为二进制值
				
        
 
            
        - 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
 - 将函数的返回值分配给引用 C++? 2022-01-01
 - 将 hdc 内容复制到位图 2022-09-04
 - XML Schema 到 C++ 类 2022-01-01
 - 哪个更快:if (bool) 或 if(int)? 2022-01-01
 - 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
 - OpenGL 对象的 RAII 包装器 2021-01-01
 - 如何提取 __VA_ARGS__? 2022-01-01
 - GDB 不显示函数名 2022-01-01
 - DoEvents 等效于 C++? 2021-01-01
 
						
						
						
						
						