1

I'm looking for suggestions on how to format a binary number so that after every 4th digit there's a space. I have a C program that converts a decimal number to binary but it just gives a long string with no spaces like "10000000" and I want it to be "1000 0000"

EDIT: here's the code

#include "binary.h"

char* binary(int num)
{
   int i, d, count;
   char *pointer;

   count = 0;
   pointer = (char*)malloc(32+1);

   if(pointer == NULL)
     exit(EXIT_FAILURE);

   for (i = 31; i >= 0; i--)
   {
      d = num >> i;

       if (d & 1)
         *(pointer + count) = 1 + '0';
       else
         *(pointer + count) = 0 + '0';

       count++;
    }
    *(pointer+count) = '\0';

    return pointer;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user3000731
  • 93
  • 2
  • 11

4 Answers4

3

Try these changes:

Change your malloc to:

pointer = malloc(32+7+1); /* 32 digits + 7 spaces + null */

and add the following into your loop right before count++;:

/* if i is non-zero and a multiple of 4, add a space */
if (i && !(i & 3)) {
  count++;
  *(pointer + count) = ' ';
}
Dmitri
  • 9,175
  • 2
  • 27
  • 34
0
#include <stdio.h>
#include <string.h>

void
printbin(unsigned v)
{
    size_t e = sizeof(v) * 10;
    char s[e+1];

    s[e--] = 0;

    for (; v || e % 5; v >>= 1) {
        if (e % 5 == 0) s[e--] = ' ';
        s[e--] = (v & 1) ? '1' : '0';
    }

    printf("%s\n", &s[e+1]);
}
user3125367
  • 2,920
  • 1
  • 17
  • 17
0
#include <limits.h>

char* binary(int num){
    int i, count, bits = sizeof(num)*CHAR_BIT;
    char *pointer = malloc(bits + (bits / 4 -1) + 1);//for bit, for space, for EOS

    if(pointer == NULL){
        perror("malloc at binary");
        exit(EXIT_FAILURE);
    }

    count = 0;
    for (i=bits-1; i >= 0; i--){
        pointer[count++] = "01"[(num >> i) & 1];
        if(i && (count+1) % 5 == 0)
            pointer[count++] = ' ';
    }
    pointer[count] = '\0';

    return pointer;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
-1

Well one way is to convert this binary number into string variable, and then you put a space between each fourth and fifth digit. Here is a tip how to convert int to string.

Community
  • 1
  • 1
Gašper Sladič
  • 867
  • 2
  • 15
  • 32