Integer/Character converter to binary

This is a discussion on Integer/Character converter to binary within the C Programming forums, part of the General Programming Boards category; I wrote this code purely for educational purposes. It also helped learn more about how exactly things look in memory, ...

  1. #1
    Registered User
    Join Date
    Jan 2013
    Posts
    55

    Integer/Character converter to binary

    I wrote this code purely for educational purposes. It also helped
    learn more about how exactly things look in memory, so it helped me in that aspect. I'm posting this in order to obtain any suggestions you may have on the code I have right now ( I will likely add more and change it in the future)

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    #include <ctype.h>
    
    
    #define LINE "\n--------------------------------------------------------------------------------\n"
    
    
    char * int2bin(int number);
    void DrawLine();
    
    
    int main()
    {
        char ans = ' ';
        char cinput = ' ';
        int input = 0;
        char * memoryallocated;
    
    
        DrawLine();
        printf("   Do you want to translate integers or \ncharacters to binary? [i/c]\n\n");
        scanf("%1c", &ans);
        DrawLine();
    
    
        if (toupper(ans) == 'I') {
            printf("Type in a number and press enter to convert a number to binary! \n");
            DrawLine();
        do
        {
            fflush(stdin);
            scanf("%d", &input );
            DrawLine();
            memoryallocated = int2bin(input);
            DrawLine();
            if (memoryallocated != NULL) { free(memoryallocated); } else {exit(1); break;}
        } while (1);
        } else if (toupper(ans) == 'C') {
            printf("Type in a character and press enter to convert it to binary! \n");
            DrawLine();
            do {
            fflush(stdin);
            scanf("%1c", &cinput );
            DrawLine();
            memoryallocated = int2bin((int)cinput);
            DrawLine();
            if (memoryallocated != NULL) { free(memoryallocated); } else {exit(1); break;}
            } while(1);
        }
    
    
        return 1;
    }
    
    
    char * int2bin(int number)
    {
        char * StartOfBin;
        char * BinPtr;
        size_t MemAmount;
        int bitnum = 4;
        int charbyteamount = 1;
        int PlaceValue;
        int n = 0;
        int ctr = 0;
        int * tempmem = (int *)malloc(1 * sizeof(int));
        *(tempmem + 0) = number;
    
    
        do
        {
            if (number <= (pow(2, bitnum) - 1)) {StartOfBin = (char*)malloc(MemAmount = (sizeof(char)* ((4 * charbyteamount) + 1))); break; }
            bitnum *= 2;
            charbyteamount *= 2;
        } while (1);
    
    
        BinPtr = StartOfBin;
    
    
        if ( StartOfBin != NULL ) {
            for(; n < (MemAmount - 1); n++) { *(BinPtr + n) = '0'; }
            *(BinPtr + (n)) = '\0';
        } else return NULL;
    
    
        BinPtr = StartOfBin;
        PlaceValue = (pow(2,n)/2);
    
    
        do
        {
            if (number >= PlaceValue) {
                    *(BinPtr + 0) = 0b00110001; // '1'
                    number -= PlaceValue;
                    PlaceValue /= 2;
                    BinPtr++;
                    ctr++;
                    } else {
                    PlaceValue /= 2;
                    BinPtr++;
                    ctr++;
                    }
        } while (ctr < n);
    
    
        printf("%d = %s \n", *(tempmem+0), StartOfBin);
        free(tempmem);
    
    
        return StartOfBin;
    }
    
    
    void DrawLine() { printf("%s", LINE); }

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,500
    It's not looking too bad, but here are some improvements.

    Indentation (see SourceForge.net: Indentation - cpwiki) could be better in places.
    In particular, code following an opening brace is a no-no.

    > int * tempmem = (int *)malloc(1 * sizeof(int));
    Do not cast malloc in a C program.
    If you get a warning about "cannot convert void*", then you need to stop using a C++ compiler to compile C code (perhaps change prog.cpp to prog.c).

    > *(BinPtr + 0) = 0b00110001; // '1'
    Not all compilers support binary constants.
    You may as well have said *(BinPtr + 0) = '1';
    and saved you the trouble of writing a comment.

    > fflush(stdin);
    NO.
    SourceForge.net: Fflush - cpwiki

    > int main .... return 1;
    The successful return from main should be return 0; or return EXIT_SUCCESS;

    > if (toupper(ans) == 'I')
    Create a pair of functions to make main tidier.
    Say
    Code:
    if (toupper(ans) == 'I') {
      doIntegerConversion();
    } else if (toupper(ans) == 'C') {
      doCharacterConversion();
    }
    and move the respective blocks of code into the separate functions.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Jan 2013
    Posts
    55
    Hello again, in response to Salem's post I have made several changes...

    1) It is now possible to break out of the loop to exit and change which conversion you are using.

    2) I removed the casting of malloc()

    3) I replaced fflush(stdin) with getchar(). ( I still needed a way to "clean" the buffer, and I knew a call to getchar() could work )

    4) Replaced the 0b00110001 binary number with plain old '1' in single quotes.

    5) Moved the 2 conversions into different functions, as Salem suggested.

    6) Improved and re-checked indentation

    That's all the updates I made to the program now. Feel free to post anything I missed or made a mistake on in the new code.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    #include <ctype.h>
    
    #define LINE "\n--------------------------------------------------------------------------------\n"
    
    char * int2bin(int number);
    void IntegerToBinaryConversion();
    void CharacterToBinaryConversion();
    void DrawLine();
    
    int main()
    {
        char ans = ' ';
    
        DrawLine();
    
        do {
                printf("   Do you want to translate integers or \ncharacters to binary? (press e to exit) [i/c/e]\n\n");
                scanf("%1c", &ans);
                DrawLine();
    
                switch(toupper(ans))
                {
                case 'C' :
                    printf("Type in a character and press enter to convert it to binary! \n");
                    DrawLine();
                    CharacterToBinaryConversion();
                    break;
                case 'I' :
                    printf("Type in a number and press enter to convert a number to binary! \n");
                    DrawLine();
                    IntegerToBinaryConversion();
                    break;
                case 'E' : break;
                }
            getchar();
            
        } while (toupper(ans) != 'E');
    
        return 0;
    }
    
    char * int2bin(int number)
    {
        char * StartOfBin;
        char * BinPtr;
        size_t MemAmount;
        int bitnum = 4;
        int charbyteamount = 1;
        int PlaceValue;
        int n = 0;
        int ctr = 0;
        int * tempmem = malloc(1 * sizeof(int));
        *(tempmem + 0) = number;
    
        do
        {
            if (number <= (pow(2, bitnum) - 1)) {StartOfBin = malloc(MemAmount = (sizeof(char)* ((4 * charbyteamount) + 1))); break; }
            bitnum *= 2;
            charbyteamount *= 2;
    
        } while (1);
    
        BinPtr = StartOfBin;
    
        if ( StartOfBin != NULL )
        {
            for(; n < (MemAmount - 1); n++) { *(BinPtr + n) = '0'; }
            *(BinPtr + (n)) = '\0';
    
        } else return NULL;
    
        BinPtr = StartOfBin;
        PlaceValue = (pow(2,n)/2);
    
        do
        {
            if (number >= PlaceValue)
            {
                *(BinPtr + 0) = '1';
                number -= PlaceValue;
                PlaceValue /= 2;
                BinPtr++;
                ctr++;
    
            } else {
                PlaceValue /= 2;
                BinPtr++;
                ctr++;
    
            }
        } while (ctr < n);
    
        printf("%d = %s \n", *(tempmem+0), StartOfBin);
        free(tempmem);
    
        return StartOfBin;
    }
    
    void DrawLine() { printf("%s", LINE); }
    
    void IntegerToBinaryConversion()
    {
        int input = 0;
    
        getchar();
        scanf("%d", &input );
    
        DrawLine();
        char * memoryallocated = int2bin(input);
        DrawLine();
    
        if (memoryallocated != NULL) { free(memoryallocated); } else {exit(1);}
    
        return;
    }
    
    void CharacterToBinaryConversion()
    {
        char cinput = ' ';
    
        getchar();
        scanf("%1c", &cinput );
    
        DrawLine();
        char * memoryallocated = int2bin((int)cinput);
        DrawLine();
    
        if (memoryallocated != NULL) { free(memoryallocated); } else {exit(1);}
    
        return;
    }

  4. #4
    Registered User
    Join Date
    May 2012
    Posts
    333
    You can make inttobin a lot tighter.
    I'm the author of MiniBasic: How to write a script interpreter and Basic Algorithms
    Visit my website for lots of associated C programming resources.
    http://www.malcolmmclean.site11.com/www

  5. #5
    Registered User
    Join Date
    Jun 2011
    Posts
    2,292
    Why not create another function that is responsible for receiving user input? This way you can keep the code used to clear the input buffer all in one place.

    For instance, have a function that calls "fgets()", and use "sscanf()" to extract the information you need, which you can return to the calling function.

    Use the return value of "sscanf()" to determine if items were successfully read from your string.

    Also, "fgets()" stores the newline as part of the string, if there is room for it. Based on this, you can do a simple check as follows - if the entered string ends in a newline, you know the entire line entered by the user has been read, therefore there is no need to clear the input buffer. If there is *no* newline in that string, then you know that there are extra characters floating around the input buffer, which can be eaten up by a simple loop using "getchar()".

  6. #6
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,302
    *(BinPtr + n) etc can be replaced with BinPtr[n] same with anywhere else you use that form of syntax.

    Don't use pow where a bit-shift can be used instead. That's using a sledgehammer to crack a nut.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  7. #7
    Registered User
    Join Date
    May 2013
    Posts
    4
    when l compiled it, it gave me errors: gcc -Wall -Werror -O -o program program.c
    /tmp/ccbTt6Ih.o: In function `int2bin':
    ggg.c: (.text+0x4f): undefined reference to `pow'
    ggg.c: (.text+0xc6): undefined reference to `pow'
    collect2: ld returned 1 exit status
    why does it give me these errors? how can l fix them?

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,652
    You may need to link to the math library, e.g., by using the -lm option.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. character converter
    By Sotiris Kaniras in forum C Programming
    Replies: 38
    Last Post: 03-13-2013, 01:21 PM
  2. Hex to Binary Converter
    By Fields in forum C Programming
    Replies: 12
    Last Post: 09-25-2012, 07:42 PM
  3. binary converter
    By cerin in forum C++ Programming
    Replies: 5
    Last Post: 04-18-2005, 04:52 PM
  4. Help with Error - Binary to Character Converter
    By dvldrmmr in forum C++ Programming
    Replies: 7
    Last Post: 04-30-2004, 01:21 PM
  5. Binary converter
    By CheesyMoo in forum C++ Programming
    Replies: 2
    Last Post: 02-18-2003, 09:27 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21