I have the code below which should convert an user message input to its bits counterpart. For example "Hi!" should be converted to 01001000 01001001 00100001
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
int printbulbs(int ascii_input);
int main(void)
{
char *Mesaj = get_string("Message: ");
int size = strlen(Mesaj);
int *ascii_conversion = malloc(size * sizeof(int));
for( int i =0; i < size; i++)
{
ascii_conversion[i] = (int)Mesaj[i];
}
for ( int i = 0; i<size; i++)
{
printbulbs(ascii_conversion[i]);
}
free(ascii_conversion);
}
int printb(int ascii_input)
{
int bits = sizeof(int) * 8;
char* bits_message = malloc(bits+ 1);
bits_message[bits] ='\0';
for (int i= bits-1; i>=0; i--)
{
bits_message[i] = (ascii_input & 1) + '0';
ascii_input >>= 1;
}
printf("%s\n", bits_message);
free(bits_message);
return 0;
}
Running the code I get the below result:
Message: Hi! 00000000000000000000000001001000 00000000000000000000000001101001 00000000000000000000000000100001
But the correct result should be:
Message: Hi! 01001000 01001001 00100001
If sizeof( int )
is equal to 4
then you have that the expression used as an initializer in this declaration
int bits = sizeof(int) * 8;
is equal to 32
.
Also to output bits there is no great sense to allocate dynamically an array as you are doing
int *ascii_conversion = malloc(size * sizeof(int));
//...
char* bits_message = malloc(bits+ 1);
Pay attention to that the code has a typo in the function name.
On the one hand, the function is called like
printbulbs(ascii_conversion[i]);
^^^^^^^^^^
But in its definition its name is different
int printb(int ascii_input)
^^^^^^^
Also the return type int
does have a useful information. It would be better to declare it like void
.
Here is a demonstration program that shows how the function can be declared and defined.
#include <stdio,h>
#include <limits.h>
void printbulbs( char c )
{
char bits[CHAR_BIT];
for (size_t i = 0; i < CHAR_BIT; i++)
{
bits[CHAR_BIT - i - 1] = ( c & 1 ) + '0';
c = ( unsigned char )c >> 1;
}
printf( "%.*s", CHAR_BIT, bits );
}
int main( void )
{
const char *message = "Hi!";
printf( "%s ", message );
for ( const char *p = message; *p != '\0'; ++p )
{
if (p != message) putchar( ' ' );
printbulbs( *p );
}
putchar( '\n' );
}
The program output is
Hi! 01001000 01101001 00100001