1

I'm trying to convert an integer to a binary String (see code below). I've already looked at several similar code snippets, and can't seem to find the reason as to why this does not work. It not only doesn't produce the correct output, but no output at all. Can somebody please explain to me in detail what I'm doing wrong?

#include <stdio.h>
#include <stdlib.h>

char* toBinaryString(int n) {
  char *string = malloc(sizeof(int) * 8 + 1);
  if (!string) {
    return NULL;
  }
  for (int i = 31; i >= 0; i--) {
    string[i] = n & 1;
    n >> 1;
  }
  return string;
}

int main() {
  char* string = toBinaryString(4);
  printf("%s", string);
  free(string);
  return 0;
}
7
  • 2
    n >> 1; has no effect Commented Jun 21, 2021 at 14:00
  • 2
    You should terminate the string with '\0'. Commented Jun 21, 2021 at 14:02
  • @JohnnyMopp How would I do that? Can I just write string[32] = '\0'? Commented Jun 21, 2021 at 14:04
  • @EugeneSh. If I change it to n = n >> 1, that still doesn't change the output. Commented Jun 21, 2021 at 14:05
  • Yes - or string[sizeof(int) * 8] = '\0' Commented Jun 21, 2021 at 14:05

3 Answers 3

4

The line

string[i] = n & 1;

is assigning integers 0 or 1 to string[i]. They are typically different from the characters '0' and '1'. You should add '0' to convert the integers to characters.

Also, as @EugeneSh. pointed out, the line

n >> 1;

has no effect. It should be

n >>= 1;

to update the n's value.

Also, as @JohnnyMopp pointed out, you should terminate the string by adding a null-character.

One more point it that you should check if malloc() succeeded. (It is done in the function toBinaryString, but there is no check in main() before printing its result)

Finally, It doesn't looks so good to use a magic number 31 for the initialization of for loop while using sizeof(int) for the size for malloc().

Fixed code:

#include <stdio.h>
#include <stdlib.h>

char* toBinaryString(int n) {
  int num_bits = sizeof(int) * 8;
  char *string = malloc(num_bits + 1);
  if (!string) {
    return NULL;
  }
  for (int i = num_bits - 1; i >= 0; i--) {
    string[i] = (n & 1) + '0';
    n >>= 1;
  }
  string[num_bits] = '\0';
  return string;
}

int main() {
  char* string = toBinaryString(4);
  if (string) {
    printf("%s", string);
    free(string);
  } else {
    fputs("toBinaryString() failed\n", stderr);
  }
  return 0;
}
Sign up to request clarification or add additional context in comments.

3 Comments

@chux-ReinstateMonica Thank you for pointing out. I'll fix.
Would casting the result of n & 1 to char have the same effect as adding '0' as you did here?
@RalphBear No. Casting won't change the value unless the old value doesn't fit in the range of the new type.
1

The values you are putting into the string are either a binary zero or a binary one, when what you want is the digit 0 or the digit one. Try string[i] = (n & 1) + '0';. Binary 0 and 1 are non-printing characters, so that's why you get no output.

2 Comments

There are no output not just because 0 and 1 are non-printing characters. The first element in the array will be 0, and 0 is used as a string terminator, so actually there will be no output even when it is seen as binary.
Yes, very true @MikeCAT
1
#define INT_WIDTH 32
#define TEST 1

char *IntToBin(unsigned x, char *buffer) {
    char *ptr = buffer + INT_WIDTH;
    do {
        *(--ptr) = '0' + (x & 1);
        x >>= 1;
    } while(x);
    return ptr;
}

#if TEST
    #include <stdio.h>

    int main() {
        int n;
        char str[INT_WIDTH+1]; str[INT_WIDTH]='\0';
        while(scanf("%d", &n) == 1)
            puts(IntToBin(n, str));
        return 0;   
    }
#endif

1 Comment

Please add further details to expand on your answer, such as working code or documentation citations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.