C语言整数转二进制字符串代码,

C语言标准库没有整数转二进制字符串函数,随手写一个:

#include "stdio.h"
#include <stdlib.h>
#include <string.h>

static const char *LIST[16] = {
        "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
        "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"
};

const char *getBinaryStringByIndex(const int index) {
    if (index < 0 || index > 15) {
        return NULL;
    }
    return LIST[index];
}

void printBinaryNumber(const int num, char *out) {
    int group = sizeof(num) * 8 / 4;
    int i;

    for (i = 0; i < group; i++) {
        int index = (num >> (group - i - 1) * 4) & 0x0f;
        const char *groupResult = getBinaryStringByIndex(index);
        strcpy(out + i * 4, groupResult);
    }
}

int main() {
    int a = 1997;
    int len = sizeof(a) * 8;
    char *result = (char *) calloc(len + 1, 1);

    if (!result) {
        printf("alloc memory failed");
        return -1;
    }

    printBinaryNumber(1997, result);
    printf("result: %s", result);
    free(result);

    return 0;
}

  

  

  输出如下:

猜你喜欢

转载自www.cnblogs.com/areful/p/11281700.html