c - 如何从二进制字符串转换为二进制无符号字符

标签 c

第一个问题:我有一个二进制字符串“11001”,我使用此函数将其转换为 int,该函数将其转换为 25,当我返回它时,它返回“25 x19”而不是无符号字符 11001。

第二个问题:当我输入二进制字符串“1111”时,屏蔽会一直工作,直到到达屏蔽“1000”为止,该屏蔽不起作用,但“10000”是屏蔽的最后一次迭代突然起作用了。意义: 0001 + 0010 + 0100 + 10000 = 23

而不是 0001 + 0010 + 0100 + 1000 = 15。

有什么想法吗?

我会解释我想要做什么:

  1. 我从 .txt 文件获取输入“11001”,我必须将其转换为 UNSIGNED CHAR,即“只是”11001。

我想要做的是将“11001”转换为25,然后将25转换为11001,然后将其转换为11001无符号字符。

unsigned char stringToBinary(char tmpSubjectStatus[])
{
    int tmpInteger;
    int tmpBinary = 0; //convert tmpInteger into binary number
    unsigned char tmpBinaryCh;
    int i = 0;
    int mostRightbit = 16;
    tmpInteger = atoi(tmpSubjectStatus); //Convert from string to int
    while (i < 5){
        if (((16 >> i) & tmpInteger) != 0){
            tmpBinary += (16 >> i);
        }
        i++;
    }
    tmpBinaryCh = (unsigned char)tmpBinary;
    return tmpBinaryCh;
}

完整代码如下: http://pastebin.com/QNNf3zs7

最佳答案

我不明白你在做什么,但要将一串 1 和 0 转换为整数,应执行以下操作:

unsigned char stringToBinary(char tmpSubjectStatus[])
{
    int tmpInteger = 0;
    while (*tmpSubjectStatus)
    {
        tmpInteger <<= 1;
        if (*tmpSubjectStatus == '1')
            tmpInteger += 1;
        tmpSubjectStatus++;
    }
    return (unsigned char) tmpInteger;
}

编辑:用正确的版本替换代码(小错误)。

描述:一旦看到新的数字,(二进制)数字就会向左移动 1 位,并添加新的数字(1 或 0)。第一次是多余的,但将整数值零向左移动 1 位没有效果。

关于c - 如何从二进制字符串转换为二进制无符号字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36793073/

相关文章:

c - 缓冲区溢出 esp 偏移量

c - 阻塞读取直到指定数量的字节到达

c - 错误 : called object ‘0’ is not a function

用泰勒级数计算 tan

c++ - Django 作为 mysql 代理服务器?

c - 如何检测端口是否已在 Linux 上的 C 中使用?

c - 我如何初始化双指针有什么问题?

C语言程序将数据从文件X复制到文件Y

c - 制作一个C程序来编译另一个

c - Quine 创建并执行文件