我有一个 9 位二进制字符串“111110000”,我如何向这个二进制数加 1。
我的意思不是串联(即加 1 后字符串应该是“111110001”)。
这应该适用于任何 9 位二进制字符串。
此代码是 2 的补码转换器的一部分。
我已经从事这个工作有一段时间了,但我完全迷失了。任何帮助将不胜感激。
最佳答案
这是我根据 rici 在评论中所说的实现:
#include <stdio.h>
#include <string.h>
#define SIZE 9
char const flip[] = "10"; // flip[0]='1' flip[1]='0'
main()
{
char str[SIZE+1] = "111110100"; // as in your example
str[SIZE] = '\0';
printf("number to add '1' : %s\n", str);
int index = SIZE-1;
while(index >= 0) // bit by bit from right to left
{
str[index] = flip[str[index] -'0']; //flip bit
if(str[index] == '1') // if bit flips to '1' addition is done
{
printf("result: %s\n", str);
return 0;
}
if(index ==0 ) // processed all bits still didn't finish ==> ?
{
printf("overflow!! \n");
return 0;
}
index--;
}
}
更新
#include <stdio.h>
#include <string.h>
#define SIZE 9
char const flip[] = "10";
int main()
{
int index = SIZE;
char in[SIZE+1] = "111110100", out[SIZE+2] = "0";
strcat(out, in);
while(index >= 0)
{
out[index] = flip[out[index] -'0'];
if(out[index] == '1') break;
index--;
}
printf("result %s\n", out);
}
关于c - C语言中二进制数加一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23862335/