Int to Binary Conversion explanation

前端 未结 3 1820
情深已故
情深已故 2020-12-22 12:25

My question is based on this post: Decimal to Binary and it\'s chosen solution.

I can get the chosen answer code working, but it only works for 5 bits. How do I modi

3条回答
  •  一整个雨季
    2020-12-22 13:24

    I'm not good at english, sorry. You need to adjust the local variable 'mask' too.

    #include 
    
    void getBin(int num, char *str)
    {
      *(str+8) = '\0';
      int mask = 0x80 << 1;
      while(mask >>= 1)
        *str++ = !!(mask & num) + '0';
    }
    
    int main()
    {
      char str[9];
      getBin(10, str);
      printf("%s\n", str);
      return 0;
    }
    

    I want to explain why this code is working well. but... I'm not good at english... I just hope it's helpful/

提交回复
热议问题