I have a problem with the output of my program, the result should be encoding A to the binary system 01000001. My result is 10111110. Can you advise me what I am doing wrong or where I have an error?
bool bits1[8];
encode_char('A', bits1);
for(int i = 0; i < 8; i++){
printf("%d", bits1[i]);
}
printf("\n");
// prints: 01000001
My output is:
10111110
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
#include <string.h>
void encode(const char character, bool bits[8]);
char decode(const bool bits[8]);
int main(int argc, char *argv[]) {
bool bits1[8];
encode('A', bits1);
for(int i = 0; i < 8; i++){
printf("%d", bits1[i]);
}
return 0;
}
void encode(const char character, bool bits[8]){
int char_val = (int) character;
int final_index = 8;
for( int i = 0; i< 8; i++){
final_index--;
if(char_val % 2 == 0){
bits[final_index ] = 1;
} else {
bits[final_index ] = 0;
}
char_val = char_val / 2;
}
}
>Solution :
Since the array is a function argument, it behave the same as a pointer. This is how it works in C. In that case, sizeof don’t get you the size of the whole array, but the size of a pointer.
Since your array has a fixed size, simply use that size:
void encode(const char character, bool bits[8]){
int char_val = (int) character;
int final_index = 8;
for( int i = 0; i< 8; i++){
// ..
}
}
If you don’t want to repeat yourself, in C you can define macros. The preprocessor will take care of doing the copy paste and not you:
#define BITS_SIZE 8
void encode(const char character, bool bits[BITS_SIZE]){
int char_val = (int) character;
int final_index = 8;
for( int i = 0; i< BITS_SIZE; i++){
// ..
}
}