c - C语言中二进制数加一?

标签 c binary

我有一个 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/

相关文章:

bash - 如何只获取二进制文件的前十个字节

c - 如何使用 winpcap 停止捕获?

c - 实现一个新的strcpy函数重新定义库函数strcpy?

Python 全局函数,如 'print'

c - stat() 是如何工作的?

sql - 为什么数据库模式通常包含 32、64、128 等

c# - 如何将字符串反转为二进制

binary - 二郎 - 校验和

c - C 中整数的大小

c++ - 在 C++ 中以长度指示器方式从二进制文件中读取