citoa

itoa providing 7-bit output to character input


I am trying to convert a character to its binary using inbuilt library (itoa) in C(gcc v-5.1) using example from Conversion of Char to Binary in C , but i'm getting a 7-bit output for a character input to itoa function.But since a character in C is essentially an 8-bit integer, i should get an 8-bit output.Can anyone explain why is it so??

code performing binary conversion:

enter for (temp=pt;*temp;temp++)
{
    itoa(*temp,opt,2);        //convert to binary
    printf("%s \n",opt);            
    strcat(s1,opt);           //add to encrypted text
}

PS:- This is my first question in stackoverflow.com, so sorry for any mistakes in advance.


Solution

  • You could use printf( "%2X\n", *opt ); to print a 8-bit value as 2 hexadecimal symbols.

    It would print the first char of opt. Then, you must increment the pointer to the next char with opt++;.

    The X means you want it to be printed as uppercase hexadecimal characters (use x for lowercase) and the 2 will make sure it will print 2 symbols even if opt is lesser than 0x10.
    In other words, the value 0xF will be printed 0x0F... (actually 0F, you could use printf( "%#2X\n", *opt ); to print the 0x).

    If you absolutely want a binary value you have to make a function that will print the right 0 and 1. There are many of them on the internet. If you want to make yours, reading about bitwise operations could help you (you have to know about bitwise operations if you want to work with binaries anyways).

    Now that you can print it as desired (hex as above or with your own binary function), you can redirect the output of printf with the sprintf function.

    Its prototype is int sprintf( char* str, const char* format, ... ). str is the destination.

    In your case, you will just need to replace the strcat line with something like sprintf( s1, "%2X\n", *opt); or sprintf( s1, "%s\n", your_binary_conversion_function(opt) );.

    Note that using the former, you would have to increment s1 by 2 for each char in opt because one 8-bit value is 2 hexadecimal symbols.

    You might also have to manage s1's memory by yourself, if it was not the case before.

    Sources :
    MK27's second answer
    sprintf prototype