Convert binary format string to int, in C

前端 未结 7 597
刺人心
刺人心 2020-12-01 21:21

How do I convert a binary string like \"010011101\" to an int, and how do I convert an int, like 5, to a string \"101\" in C?

7条回答
  •  借酒劲吻你
    2020-12-01 22:01

    To answer the second part of the question.

    char* get_binary_string(uint16_t data, unsigned char sixteen_bit)
    {
        char* ret = NULL;
        if(sixteen_bit) ret = (char*)malloc(sizeof(char) * 17);
        else ret = (char*)malloc(sizeof(char) * 9);
        if(ret == NULL) return NULL;
    
        if(sixteen_bit){
            for(int8_t i = 15; i >= 0; i--){
                *(ret + i) = (char)((data & 1) + '0');
                data >>= 1;
            }
            *(ret + 16) = '\0';
            return ret;
        }else{
            for(int8_t i = 7; i >= 0; i--){
                *(ret + i) = (char)((data & 1) + '0');
                data >>= 1;
            }
            *(ret + 8) = '\0';
            return ret;
        }
        return ret;
    }
    

提交回复
热议问题