Thread: Converting ASCII to Binary in C++

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    15

    Converting ASCII to Binary in C++

    Hi guys I'm trying to write a program to convert ASCII code into binary but it is not working properly.

    Code:
    #include <iostream>
    #include <cmath>
    
    using namespace std;
    
    int main()
    {
        char character;
        int i;
        int m[8];
    
    
        cout<<"Please enter a character: ";
        cin>>character;
        cout<<"You've entered "<<character<<endl;
    
        for(i=0;i<8;i++)
        {
            m[i]=character%2;
            character = character/2;
        }
    
        int top, bottom;
    
        for(bottom=0,top =7; bottom<8; bottom++,top--)
        {
            m[bottom]=m[top];
            cout<<m[top];
        }
    
        return 0;
    }
    This is what I have so far. It works for the letter 'A' but it also output the identical binary number for B or C and it goes completely crazy if I type in 'V'.

    Please help me find the error.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > m[bottom]=m[top];
    What does this do?

    Try it without it.
    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.

  3. #3
    Registered User
    Join Date
    Nov 2010
    Posts
    15
    Wow thank you. I have no idea what I was thinking.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Converting Integer to ASCII
    By Kurdo in forum C Programming
    Replies: 15
    Last Post: 01-08-2011, 01:14 PM
  2. Converting From Binary Tree to Threaded Binary Trees
    By elton_fan in forum C Programming
    Replies: 15
    Last Post: 11-08-2007, 11:41 PM
  3. Converting words into ASCII values
    By manutdfan in forum C Programming
    Replies: 3
    Last Post: 01-22-2007, 12:22 PM
  4. converting chars to ascii equivilant
    By Unregistered in forum C++ Programming
    Replies: 3
    Last Post: 09-01-2001, 12:03 PM