Thread: Dec to Bin

  1. #1

    Dec to Bin

    Hey,

    It has been a while since I've programmed in C++, but some school thing just turned up and it came in handy.

    I've created a function to make a binary code from any number under 255, (ASCII -> Bin) but it seems a bit long and simple, I was wondering if there was a easier more neat way of doing it. But at the same time it shouldn't become a string, they should stay intergers, and if possible in an array.

    This works for me:

    Code:
    void ascii_bin(int ascii_v)
    {
        int binary[7];
        if(ascii_v<128)
        {
            binary[0] = 0;
        }else{
            binary[0] = 1;
            ascii_v -= 128;
        }
        if(ascii_v<64)
        {
            binary[1] = 0;
        }else{
            binary[1] = 1;
            ascii_v -= 64;
        }
        if(ascii_v<32)
        {
            binary[2] = 0;
        }else{
            binary[2] = 1;
            ascii_v -= 32;
        }
        if(ascii_v<16)
        {
            binary[3] = 0;
        }else{
            binary[3] = 1;
            ascii_v -= 16;
        }
        if(ascii_v<8)
        {
            binary[4] = 0;
        }else{
            binary[4] = 1;
            ascii_v -= 8;
        }
        if(ascii_v<4)
        {
            binary[5] = 0;
        }else{
            binary[5] = 1;
            ascii_v -= 4;
        }
        if(ascii_v<2)
        {
            binary[6] = 0;
        }else{
            binary[6] = 1;
            ascii_v -= 2;
        }
        if(ascii_v<1)
        {
            binary[7] = 0;
        }else{
            binary[7] = 1;
            ascii_v -= 1;
        }
        return binary;
    }
    Btw, is it possible to return an array? Or should I go about doing it some other way? And can I take an array and give it to a function as a variable to use?

    Thanks in advanced

    Devouring One
    Last edited by devour89; 10-04-2004 at 09:45 AM.
    Dev C++
    Win XP/2k/98

    I DO NOT TAKE CLASSES I DONT GET HOMEWORK THIS IS NOT A HOMEWORK QUESTION!!!

    He's lean he's keen... He's the spank machine!

  2. #2
    Registered User
    Join Date
    Aug 2003
    Posts
    1,218
    look up bitset(s??).

  3. #3
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    As suggested, a bitset is very easy to use and would shorten all of that code down to perhaps a single line depending on how you implement things. One short example of using a bitset:

    Code:
    #include <iostream>
    #include <bitset>
    
    int main()
    {
        std::bitset<8> bits; // Create bitset object to hold a value with up to 8 bits
    
        bits = 218;          // Initialize bitset to an integer value
        std::cout << bits;   // Output binary representation of 218
    
        return 0;
    }
    Outputs: 11011010

    Quote Originally Posted by devour89
    Btw, is it possible to return an array? Or should I go about doing it some other way? And can I take an array and give it to a function as a variable to use?
    Returning a local array? No, unless you are doing some dynamic allocation within the function and returning a pointer to the allocated memory or returning the address of a static array. If it is a local array then once the function exits, the memory on the stack where your array used to exist can be overwritten by something else, a potentially dangerous thing to have happen.

    You can pass in an array into your function which can be operated upon by that function. Once the function exits, any changes made by that function to the array should remain in place.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  4. #4
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    >>I was wondering if there was a easier more neat way of doing it--probably

    >>they should stay intergers, and if possible in an array.---sounds doable. Now that you've got workable code, try to modify is such a way as to achieve your goal.


    >>is it possible to return an array? No

    >>Or should I go about doing it some other way? Yes

    >>And can I take an array and give it to a function as a variable to use? Yes

  5. #5
    Thank you hk_mp5kpdw,

    The code works like a charm, my only question left is can I seperate all the '0' and '1' into an array?
    Eg
    Code:
    //dec=101
    bin[0] = 0;
    bin[1] = 1;
    bin[2] = 1;
    bin[3] = 0;
    bin[4] = 0;
    bin[5] = 1;
    bin[6] = 0;
    bin[7] = 1;
    Dev C++
    Win XP/2k/98

    I DO NOT TAKE CLASSES I DONT GET HOMEWORK THIS IS NOT A HOMEWORK QUESTION!!!

    He's lean he's keen... He's the spank machine!

  6. #6
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Quote Originally Posted by devour89
    my only question left is can I seperate all the '0' and '1' into an array?
    Array of characters, or array of integers 1s and 0s? One way perhaps (for a character array), use the bitset to_string() member function along with the string c_str() member function to get a c-style character string representation of the bitset that you can then strcpy into a temp array.

    Code:
    #include <cstring>
    #include <bitset>
    #include <iostream>
    #include <string> // Not sure if needed in this instance, just in case
    
    int main()
    {
        std::bitset<8> bits(218);
        char array[9];  // Extra space to hold NULL copied during strcpy
    
        strcpy(array,bits.to_string().c_str());
    
        std::cout << array << std::endl;
    
        return 0;
    }
    Again, should output: 11011010

    Edit: Forgot to mention that you can use the array indexing operator [] to access individual bits from the bitset in an array like manner which can be used in a loop to initialize an array. I.e. for the bitset in the above example we have:

    bits[0] = 0
    bits[1] = 1
    bits[2] = 0
    bits[3] = 1
    bits[4] = 1
    bits[5] = 0
    bits[6] = 1
    bits[7] = 1

    Using that principal might be useful for you.
    Last edited by hk_mp5kpdw; 10-04-2004 at 01:18 PM.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  7. #7
    i dont know Vicious's Avatar
    Join Date
    May 2002
    Posts
    1,200
    If you dont want to use the bitset container you could try this.

    Code:
    #include <iostream>
    using namespace std;
    
    int main ()
    {
    
    	char character;
    	char bits [8];
    	int counter = 0;
    	
    	cout << "Enter an ASCII character: ";
    	cin  >> character;
    	
    	for ( int loop = 7; loop >= 0; loop -- ) {
    		
    		bits [counter] = ( ( character >> loop ) & 1 ) ? '1' : '0';
    		counter ++;
    		
    	}
    
            bits [8] = '\0';
    	
    	cout << endl;
    	cout << character << " in binary: " << bits;
    	
    	return 0;
    	
    }
    bits [8] = '\0';

    For some reason I had to do that to keep it from putting a bunch of garbage after the binary string.
    Last edited by Vicious; 10-04-2004 at 01:24 PM.
    What is C++?

  8. #8
    Registered User
    Join Date
    Aug 2003
    Posts
    1,218
    You need to put in a \0 at the end of the char array vicious.

  9. #9
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    Without using bitsets you could do this:
    Code:
    int input;
    //get input
    int x = input;
    int array[10];
    int i = 0;
    while(x > 0)
    {
      array[i++] = x % 2;
      x/2;
    }
    That will put the binary value of input in array in "backward" order where the power of 2 is the index of the element. For example:

    input = 26 would come out as 01011 if printed in ascending order of index, and 11010 if printed in descending order of index---which could be readily accomplished.

  10. #10
    i dont know Vicious's Avatar
    Join Date
    May 2002
    Posts
    1,200
    Quote Originally Posted by Shakti
    You need to put in a \0 at the end of the char array vicious.
    Hehe I just figured that out.
    What is C++?

  11. #11
    Registered User
    Join Date
    Oct 2004
    Posts
    120

    The int values of '1' and '0's...

    To get workable values from the char array, in a loop subtract the ascii value of '0' (0x30). '1' is 0x31...
    Or, instead of coverting to a string, in a loop, use a bitmask like this...
    Code:
    ...
            std::bitset<8> bits(218);
    	int mask = 1;
    	unsigned long bitArray[8] = {0};
    	unsigned long bl = bits.to_ulong(); 
    	for (int i = 7; i >=0 /*bad magic # :) */; i--, mask = mask << 1)
    	{
    		bitArray[i] = (bl & mask) >> (7 - i);
    		printf("%d", bitArray[i]);
    	}
    	printf ("\n");
    	return 0;
    Or if you want to keep everything it bitset, create the bitArray as type bitset[8] and then get rid of the extra ulong bl. Just & the mask against bits but keep everything else the same. This will put the LSB in index 0.

    PK

  12. #12
    Registered User
    Join Date
    Oct 2004
    Posts
    120
    Elad, x/2 needs to be x/=2...you've got yourself a nice inifinte loop there

  13. #13
    i dont know Vicious's Avatar
    Join Date
    May 2002
    Posts
    1,200
    Also if you need an understanding of how the bitset container works

    http://cboard.cprogramming.com/showthread.php?t=56918

    Theres a little thread I made.
    What is C++?

  14. #14
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    pabli615--sure enough. Thanks for pointing that out.

  15. #15
    Registered User
    Join Date
    Aug 2003
    Posts
    1,218
    Actually vicious there is another, even uglier bug in your code after you edited it
    Code:
    #include <iostream>
    using namespace std;
    
    int main ()
    {
    
    	char character;
    	char bits [9];
    	int counter = 0;
    	
    	cout << "Enter an ASCII character: ";
    	cin  >> character;
    	
    	for ( int loop = 7; loop >= 0; loop -- ) {
    		
    		bits [counter] = ( ( character >> loop ) & 1 ) ? '1' : '0';
    		counter ++;
    		
    	}
    
            bits [8] = '\0';
    	
    	cout << endl;
    	cout << character << " in binary: " << bits;
    	
    	return 0;
    	
    }
    Just thought I would post it so it wouldnt confuse anyone.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. adding a number to a number
    By bigmac(rexdale) in forum C Programming
    Replies: 11
    Last Post: 10-24-2007, 12:56 PM
  2. Bin packing problem....
    By 81N4RY_DR460N in forum C++ Programming
    Replies: 0
    Last Post: 08-01-2005, 05:20 AM
  3. dec -> bin -> hex in arrays
    By chris1985 in forum C Programming
    Replies: 2
    Last Post: 05-09-2005, 08:15 AM
  4. Independent-Robert Fisk-Osama
    By a muslim in forum A Brief History of Cprogramming.com
    Replies: 2
    Last Post: 10-18-2001, 08:41 PM