1

i had write a program, that convert a char to binary code... All were working when i had that code

int n, c, k;
n = character;
for (c = 7; c >= 0; c--)
  {
    k = n >> c;
 if (k & 1)
     printf("1");
    else
      printf("0");
}

But I must to write these values to an ARRAY and I edited code like u can see below and thats not worked.. Can you help me please?

void encode_char(const char character, bool bits[8]) {
int n, c, k;
n = character;
  for (c = 7; c >= 0; c--)
  {
    k = n >> c;

    if (k & 1)
      bits[c] = "1";
    else
      bits[c] = "0";
  }

  printf("\n");
}

Arena code In a Arena (that controls the program) you can see error: Assertion 'encode_char('r', bits) => {0, 1, 1, 1, 0, 0, 1, 0}' failed. [got {1, 1, 1, 1, 1, 1, 1, 1}]]

3
  • 2
    The characters '0' and '1' are both true (any non-0 value is true). Try 0 and 1 instead of the characters. Commented Nov 24, 2020 at 12:10
  • 3
    replace "if (k & 1) bits[c] = "1"; else bits[c] = "0";" with "bits[c] = k & 1;" Commented Nov 24, 2020 at 12:11
  • 2
    I suggest listening to compiler's warnings: at bits[c] = "1"; the compiler should complain because you are assigning a const cahr * to a boolean. Commented Nov 24, 2020 at 12:13

1 Answer 1

2

Here's a possible implementation for the code:

#include <stdio.h>
#include <stdbool.h>

void encode_char(char character, bool bits[8]) {
    for (int bit_index = 7; bit_index >= 0; bit_index--, character >>= 1)
        bits[bit_index] = character & 1;
}

int main() {
    bool bits[8];
    encode_char('U', bits);

    for (int bit_index = 0; bit_index < 8; bit_index++)
        printf("%d", bits[bit_index]);
    printf("\n");

    return 0;
}

Some points:

  • You don't need so many variables for the bits extraction logic, you're already creating a new variable in the function, so just change its value.
  • Like the comments stated, you're comparing a bit and not a byte.
Sign up to request clarification or add additional context in comments.

1 Comment

I just must created variable n, n=character, because of character must be const, but otherwise it works. Thanks.

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.