linux 下實現 itoa 轉二進制

linux 下,需要將整數轉化爲二進制,很自然想到 itoa,發現這函數竟然編譯不通過。標準庫中貌似有這個實現,不明白了~ 網上參考了帖子,下面實現代碼:


方法一

感覺這方法有點費腦,不是很直觀。

取模的方法一般都是從低位到高位,所以保存的字符串結果一般會跟需要的結果相反,需要倒轉,要解決這個問題,可以從字符串數組後面開始往前保存。

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

#define BUF_LEN 64

char* i2bin(unsigned long long v, char* buf, int len) {
    if (0 == v) {
        memcpy(buf, "0", 2);
        return buf;
    }

    char* dst = buf + len - 1;
    *dst = '\0';

    while (v) {
        if (dst - buf <= 0) return NULL;
        *--dst = (v & 1) + '0';
        v = v >> 1;
    }
    memcpy(buf, dst, buf + len - dst);
    return buf;
}

int main() {
    unsigned long long v;
    scanf("%llu", &v);
    char buf[BUF_LEN] = {0};
    char* res = i2bin(v, buf, BUF_LEN);
    res ? printf("data: %s, len: %lu\n", i2bin(v, buf, BUF_LEN), strlen(buf))
        : printf("fail\n");
}

方法二

參考 redis sds.c 源碼,把下面源碼的 10 改爲 2 即可。

int sdsll2str(char *s, long long value) {
    char *p, aux;
    unsigned long long v;
    size_t l;

    /* Generate the string representation, this method produces
     * an reversed string. */
    v = (value < 0) ? -value : value;
    p = s;
    do {
        *p++ = '0' + (v % 10); // 2 
        v /= 10; // 2
    } while (v);
    if (value < 0) *p++ = '-';

    /* Compute length and add null term. */
    l = p - s;
    *p = '\0';

    /* Reverse the string. */
    p--;
    while (s < p) {
        aux = *s;
        *s = *p;
        *p = aux;
        s++;
        p--;
    }
    return l;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章