Int to binary conversion

My question is based on this post: Decimal to Binary and the selected solution.

I can get the selected response code, but it only works for 5 bits. How to change this code to work with large numbers, for example 8 bits?

I tried just setting the character offset in the first line from 5 to 8, but failed.

void getBin(int num, char *str)
{
  *(str+5) = '\0';
  int mask = 0x10 << 1;
  while(mask >>= 1)
    *str++ = !!(mask & num) + '0';
}

and test with this code by adjusting 6-9 again according to the function above:

int main()
{
  char str[6];
  getBin(10, str);
  printf("%s\n", str);
  return 0;
}

but only the first five bits are still displayed, and then random characters are output. Can someone explain what exactly happens when I tweak these numbers so that I can get this to work for converting bits 8 (or any other size)?

0
3
void getBin(int num, char *str)
{
  *(str+8) = '\0';
  int mask = 0x80 << 1;
  while(mask >>= 1)
    *str++ = !!(mask & num) + '0';
}

main()
{
  char str[9];
  getBin(254, str);
  printf("%s\n", str);
  return 0;
}

8- 9 . , .

5- , 11111, 10000, 16 10 . 8- . 10000000. mask >>= 1, int mask = 0x10 << 1; . , x-bit, x+1. \0 x. x-bit, - 1, - 0. 2^(x-1) (2 (x-1)).

0

, . .

#include <stdio.h>

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;
}

, . ... ... , /

+1

.

.

5, 0x10, 6, 5.

8 8, 0x10, 9. 0x10 , .

, .

#define BitWidth 5

void getBin(int num, char *str)
{
  int mask = 1 << (BitWidth - 1);
  // skip the original shift left and then immediately shift right
  do {
    *str++ = !!(mask & num) + '0';
  } while (mask >>= 1);
  *str = '\0';  // by appending at the end, no need for a magic number
}  

int main()
{
  char str[BitWidth + 1];
  getBin(10, str);
  printf("%s\n", str);
  return 0;
}

Note: the above approach (and other answers) have a problem when it BitWidthmatches the width int. But this is another problem that can be easily solved with unsignedmath.

0
source

Source: https://habr.com/ru/post/1658257/


All Articles