Results 1 to 4 of 4

Thread: How do you convert a character to its binary value?

  1. #1

    Thread Starter
    Fanatic Member Wynd's Avatar
    Join Date
    Dec 2000
    Location
    In a bar frequented by colossal death robots
    Posts
    772
    I want to make a program that does this, but I need to know how to do this first. Also, how would you make a loop that goes through a string and converts all the characters?
    Alcohol & calculus don't mix.
    Never drink & derive.

  2. #2
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    This to loop through each character in a string:
    Code:
    void main() {
        string sSrc = "Hello World!";
    
        for(int i = 0; i < sSrc.length(); i++) {
            string sRes = Convert(sSrc[i]);
            cout << sRes << endl;
        }
    }
    
    string Convert(char cChar) {
        // Do what you want to it in this function
        char pcBuf[9];
    
        for(int i = 0; i < 8; i++) {
            pcBuf[i] = ((cChar >> (8-i)) & 0x1) + '0';
        }
    
        pcBuf[9] = 0;
    
        return string(pcBuf);
    }
    Not totally sure on the binary conversion there (didn't have chance to test it). If the numbers are the wrong way round just change the (8 - i) in Convert.
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

  3. #3

    Thread Starter
    Fanatic Member Wynd's Avatar
    Join Date
    Dec 2000
    Location
    In a bar frequented by colossal death robots
    Posts
    772
    Can you please tell me what headers I need to include? I am getting three errors that I can't seem to getr rid of, I will post them it is helps you at all.
    Alcohol & calculus don't mix.
    Never drink & derive.

  4. #4
    denniswrenn
    Guest
    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width