C语言 二进制字符串与数值之间的转换

tech2025-03-26  4

#include <stdio.h> #include <string.h> #include <limits.h> #include <stdlib.h> const static int LONG_BIT_COUNT = CHAR_BIT * sizeof(long); long bstoi(const char *ps, int size) { /** * 二进制转数值 */ long n = 0; for (int i = 0; i < size; ++i) { n = n * 2 + (ps[i] - '0'); } return n; } char *itobs(long n, char *ps) { /** * 数值转二进制 */ for (int j = LONG_BIT_COUNT - 1; j >= 0; --j, n >>= 1) { ps[j] = (1 & n) + '0'; } ps[LONG_BIT_COUNT] = '\0'; return ps; } int main(void) { //-------自定义实现-------- char *bs = "11111111"; long num = bstoi(bs, strlen(bs)); printf("%ld\n", num); char ps[LONG_BIT_COUNT]; printf("%s\n", itobs(num, ps)); //--------使用库函数:二进制字符串转数字-------- unsigned long num2 = strtoul(bs, NULL, 2); //第三个参数为基数 printf("%lu\n", num2); return 0; } 255 0000000000000000000000000000000000000000000000000000000011111111 255
最新回复(0)