十进制到二进制转换

发布于 2024-11-02 19:31:45 字数 507 浏览 5 评论 0原文

我正在编写一个用于十进制和二进制基数系统之间转换的函数,这是我的原始代码:

void binary(int number)
{
    vector<int> binary;

    while (number == true)
    {
        binary.insert(binary.begin(), (number % 2) ? 1 : 0);
        number /= 2;
    }

    for (int access = 0; access < binary.size(); access++)
        cout << binary[access];
}

但是直到我这样做之前它才起作用:

while(number)

两种形式之间有什么问题

while(number == true)

以及有什么区别? 提前致谢。

I was writing a function for conversion between Decimal and Binary base number systems and here's my original code:

void binary(int number)
{
    vector<int> binary;

    while (number == true)
    {
        binary.insert(binary.begin(), (number % 2) ? 1 : 0);
        number /= 2;
    }

    for (int access = 0; access < binary.size(); access++)
        cout << binary[access];
}

It didn't work however until I did this:

while(number)

what's wrong with

while(number == true)

and what's the difference between the two forms?
Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

酒儿 2024-11-09 19:31:45

当您说 while (number) 时,numberint)将转换为类型 bool。如果它为零,则变为 false,如果它非零,则变为 true

当您说 while (number == true) 时,true 会转换为 int (变为 1 ) 与您所说的 while (number == 1) 是一样的。

When you say while (number), number, which is an int, is converted to type bool. If it is zero it becomes false and if it is nonzero it becomes true.

When you say while (number == true), the true is converted to an int (to become 1) and it is the same as if you had said while (number == 1).

<逆流佳人身旁 2024-11-09 19:31:45

这是我的代码......

    #include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<unistd.h>
#include<assert.h>
#include<stdbool.h>
#define max 10000
#define RLC(num,pos) ((num << pos)|(num >> (32 - pos)))
#define RRC(num,pos) ((num >> pos)|(num << (32 - pos)))

void tobinstr(int value, int bitsCount, char* output)
{
    int i;
    output[bitsCount] = '\0';
    for (i = bitsCount - 1; i >= 0; --i, value >>= 1)
      {
             output[i] = (value & 1) + '0';
      }
}


  int main()
   {
    char s[50];
    tobinstr(65536,32, s);
    printf("%s\n", s);
    return 0;
   }

Here is my code....

    #include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<unistd.h>
#include<assert.h>
#include<stdbool.h>
#define max 10000
#define RLC(num,pos) ((num << pos)|(num >> (32 - pos)))
#define RRC(num,pos) ((num >> pos)|(num << (32 - pos)))

void tobinstr(int value, int bitsCount, char* output)
{
    int i;
    output[bitsCount] = '\0';
    for (i = bitsCount - 1; i >= 0; --i, value >>= 1)
      {
             output[i] = (value & 1) + '0';
      }
}


  int main()
   {
    char s[50];
    tobinstr(65536,32, s);
    printf("%s\n", s);
    return 0;
   }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文