Thread: Characters to binary... hexadecimal to binary

  1. #31
    I lurk
    Join Date
    Aug 2002
    Posts
    1,361
    Oops

    Code:
    const int length = 8;
    char *get_binary(const int binaryOutput);
    
    int main(int argc, char *argv[])
    {
       cout << get_binary('a');
       return 0;
    };

  2. #32
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    calling pow() for each bit! hmmmm very efficient!
    Ever heard of bitwise operators?
    bitwise & can be used to test bits. Read about it in your text books. check previous threads with search facility. Read about stringstreams and how they can help you. Try to write some code and we'll fix it up for you as long as you do your own donkey work.
    Oh yeah btw your bit string will be backwards also.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  3. #33
    Registered User
    Join Date
    Sep 2002
    Posts
    417
    I'll post the compiled version whenever I finish. I've got the binary runnings smoothly! Thanks for your help!

  4. #34
    Registered User
    Join Date
    Sep 2002
    Posts
    417
    Eibro, how would I reverse your function (i.e. pass binary values to a function and it outputs the characters)

    So if I had 011000010110001001100011, it would convert that back to "abc"

  5. #35
    Hello. I haven't really been following, but i think i may have an answer. When i did an encryption where i did bit switching, i made three things to help me. I can only remember exactly how i did two of them. I had a struct(?) that had eight single-bit fields, and i had a union between that and a char. The third thing was the function that sent the char to union.ch, and then did the switches on union.bitz.b1, etc. THen again, this may have been JAVA. I blend the two sometimes...

    Hope this is of help.

    ~Inquirer
    Compilers:
    GCC on Red Hat 8.1 (Primary)
    GCC on Mac OS X 10.2.4 (Secondary)

    Others:
    MinGW on XP

  6. #36
    I lurk
    Join Date
    Aug 2002
    Posts
    1,361
    Your request seemed like an interesting challenge, so I took it a little further than I normally would

    Code:
    #include <cmath>
    #include <iostream>
    
    struct bitstring
    {
    	unsigned char bits[8];
    };
    
    bitstring get_binary(const char code)
    {
    	bitstring returnstring;
    	memset(reinterpret_cast<void *>(&returnstring), '\0', sizeof(returnstring));
    
    	int count = 0;
    	for (int bit = 128; bit >= 1; bit >>= 1)
    	{
    		returnstring.bits[count] = (code & bit) ? '1' : '0';
    		count++;
    	}
    	return returnstring;
    };
    
    
    char get_character(const bitstring instring)
    {
    	char cReturn = '\0';
    
    	int count = 0;
    	for (int bit = 128; bit >= 1; bit >>= 1)
    	{
    			if (instring.bits[count] == '1')
    			{
    				cReturn |= bit;
    			}
    			count++;
    	}
    	return cReturn;
    };
    
    int main(int argc, char* argv[])
    {
    	using namespace std;
    
    	bitstring output = get_binary('1');
    	char input = get_character(output);
    	cout << input;
    
    	return 0;
    }
    Oh, and Stoned_Coder, i've dropped the pow... as you suggested.
    Last edited by Eibro; 10-26-2002 at 06:40 PM.

  7. #37
    Eibro, could you explain how this works? Especially the part that says ...<void *>... ?

    And, i had to tweak it as follows so it would display correctly.
    Code:
    #include <cmath>
    #include <iostream>
    
    struct bitstring
    {
    	unsigned char bits[9]; // I made this to leave room for '\0'
    };
    
    bitstring get_binary(const char code)
    {
    	bitstring returnstring;
    	memset(reinterpret_cast<void *>(&returnstring), '\0', sizeof(returnstring));
    
    	int count = 0;
    	for (int bit = 128; bit >= 1; bit >>= 1)
    	{
    		returnstring.bits[count] = (code & bit) ? '1' : '0';
    		count++;
    	}
       returnstring.bits[8]='\0'; // I added this
    	return returnstring;
    };
    
    
    char get_character(const bitstring instring)
    {
    	char cReturn = '\0';
    
    	int count = 0;
    	for (int bit = 128; bit >= 1; bit >>= 1)
    	{
    			if (instring.bits[count] == '1')
    			{
    				cReturn |= bit;
    			}
    			count++;
    	}
    	return cReturn;
    };
    
    void binary()
    {
    	using namespace std;
    
    	bitstring output = get_binary((char)getche());
    	char input = get_character(output);
    	cout << "\"" << input << "\"" << endl;
       cout << output.bits << endl;
       if (getche());
    
    	return;
    }
    Compilers:
    GCC on Red Hat 8.1 (Primary)
    GCC on Mac OS X 10.2.4 (Secondary)

    Others:
    MinGW on XP

  8. #38
    I lurk
    Join Date
    Aug 2002
    Posts
    1,361
    memset(reinterpret_cast<void *>(&returnstring), '\0', sizeof(returnstring));

    reinterpret_cast<void *>(&returnstring) is using C++ style casting to cast a void pointer on the address of returnstring. Using C-Style casting it'd be (void *)&returnstring

    Also, changing the number of bits to 9 was unnessicary, i'm only using 8 characters (0-7). The 8th contains the null terminator.

    128, 64, 32, 16, 8, 4, 2, 1... There's only 8 values there, these are the ones i'm using.

    Anything else need clarification?

  9. #39
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    Uhh... yeah What's the advantage of using c++-casting instead of C casting?
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  10. #40
    ummm... yes...

    1) why exactly would you WANT to cast something into a void pointer?

    2) About the bits[9], if you output it to the screen, it also outputs he next few variables because when you say bits[8] you are setting aside memory for bits[0] to bits[7], not bits[0] to bits[8].
    the null terminator gets put in the last one later, and all 8 bits are outputted to the screen.

    3) What does memset do? I haven't done much memory stuff...

    4) What is the memset prototype?

    5) I don't exactly see how the loop(s) work to translate them to and from the binary... I get how you are stepping down the 128...1 ladder, but how do you use that to calculate whether the bit was on or off??? ::
    [EDIT]
    I have figured out #5... except for the following:
    Code:
    returnstring.bits[count] = (code & bit) ? '1' : '0';
    I can see that this would only leave the bit in question set, but i don't see how this would test true. Does null evaluate to false? That must be it...


    Thanks for the example! I learned a lot!
    [/EDIT]

    Thanks...
    ~Inquirer
    Last edited by Inquirer; 10-26-2002 at 09:02 PM.
    Compilers:
    GCC on Red Hat 8.1 (Primary)
    GCC on Mac OS X 10.2.4 (Secondary)

    Others:
    MinGW on XP

  11. #41

    kinda offsubject, but...

    Anyone who knows JAVA should help on this one...

    Is it java or c++ (or both) that have unions?
    Is it java or c++ (or both) that have single-bit data members?
    [DELETED][/DELETED]

    ~Inquirer
    Compilers:
    GCC on Red Hat 8.1 (Primary)
    GCC on Mac OS X 10.2.4 (Secondary)

    Others:
    MinGW on XP

  12. #42
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    Both might have unions (I haven't touched java for a while), but I'm pretty sure only c++ has single-bit data members.

    And about casting to a void pointer, that's 'cuz memset takes a void pointer (well, I'm guessing that), and some compilers won't do the typecast automatically. But I still don't see why he didn't just use (void*)...

    memset(sometype *pointerToDataStructureOrVariableButProbablyDataSt ructure, char valueToSetTo, int howManyBytesToSet)

    -sometype is probably either void or char - i'm guessing void, 'cuz otherwise eibros wouldn't have typecasted the thing to void.
    -valueToSetTo might be int or unsigned char.
    -howManyBytesToSet may be a long or something.
    -valueToSetTo is usually set to 0.
    -howManyBytesToSet is usually filled in with sizeof(the datastructure).
    -memset is usually used to clear out a datastructure.
    -another way to clear out a datastructure would be to use ZeroMemory(), which is either a macro or inline function or something that uses memset() and just fills in valueToSetTo with 0.
    Last edited by Hunter2; 10-26-2002 at 09:59 PM.
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  13. #43
    I lurk
    Join Date
    Aug 2002
    Posts
    1,361
    Yes, it's typecasted to void * because that's what memset takes. C++ allows for many different casts: dynamic_cast<> static_cast<> reinterpret_cast<> const_cast<>, I'm guessing these employ better typesafty and more efficient casting than the regular C-Style casting. (someone who knows more about this, please, please post)

    About bits[9], I still don't see how i'm using more than 8 elements. 0-7 is all i'm using. You're correct in adding bits[8] = '\0' though. When I declare bits[8] I get 9 elements- 0-7 are useable to me, and #8 is the null terminator. "h, e, e, l, l, l, o, o, '\0'"

    memset(void *, int, size_t); is the prototype for memset.

    Code:
    returnstring.bits[count] = (code & bit) ? '1' : '0';
    We're taking 'bit' (which is 128, 64, 32, 16, 8, 4, 2, or 1... binary digits) and ANDing with 'code'. If both 'code' and 'bit' have the particular bit set, then it returns true. If 'code' doesn't have the bit set, it returns false.

    Take the letter 'a': 01100001
    Now, throughout the loop, bit is set to 00000001, 00000010, 00000100, 00001000, 00010000, 00100000, 01000000.
    Throughout the loop, the entries bolded are the ones which return true.

  14. #44
    I lurk
    Join Date
    Aug 2002
    Posts
    1,361
    Well i'm stumped...
    Well, I was stumped. (Those two lines were written a half hour apart)

    I'm wondering why output's bits weren't retaining the value returned from the function...
    Something to do with it going out of scope? Shouldn't the object be copied?

    Oh well, I came up with this:
    Code:
    // ****msvc.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    
    #include <cmath>
    #include <iostream>
    #include <assert.h>
    
    class bitstring
    {
    public:
    
    	bitstring();
    	bitstring(const bitstring &bs);
    	~bitstring();
    
    	unsigned char *getbits();
    	void setbit(int bitnum, int val);
    	unsigned char getbit(int bitnum);	
    
    	void setbitstring(const char code);
    	char getcharacter();
    
    private:
    	unsigned char *bits;
    };
    
    bitstring::bitstring()
    {
    	bits = new unsigned char[8];
    	memset(reinterpret_cast<void *>(bits), 8, sizeof(bits));
    }
    
    
    bitstring::~bitstring()
    {
    	delete[] bits;
    }
    
    bitstring::bitstring(const bitstring &bs)
    {
    	bits = new unsigned char[8];
    
    	for (int i = 0; i < 8; i++)
    	{
    		bits[i] = bs.bits[i];
    	}
    	bits[8] = '\0';
    }
    
    
    unsigned char *bitstring::getbits()
    {
    	return bits;
    }
    
    void bitstring::setbit(int bitnum, int val)
    {
    	assert(bitnum < 8);
    	bits[bitnum] = val;
    }
    
    unsigned char bitstring::getbit(int bitnum)
    {
    	assert(bitnum < 8);
    	return bits[bitnum];
    }
    
    char bitstring::getcharacter()
    {
    	char cReturn = '\0';
    
    	int count = 0;
    	for (int bit = 128; bit >= 1; bit >>= 1)
    	{
    			if (getbit(count) == '1')
    			{
    				cReturn |= bit;
    			}
    			count++;
    	}
    	return cReturn;
    };
    
    void bitstring::setbitstring(const char code)
    {
    	int count = 0;
    	for (int bit = 128; bit >= 1; bit >>= 1)
    	{
    		setbit(count, (code & bit) ? '1' : '0');
    		count++;
    	}
    	bits[8] = '\0';
    };
    
    int main(int argc, char* argv[])
    {
    	using namespace std;
    
    	bitstring output;
    	output.setbitstring('a');
    
    	cout << output.getbits() << endl;
    
    	cin.get();
    	return 0;
    };
    Looks like I went a little overboard...
    Last edited by Eibro; 10-27-2002 at 12:01 AM.

  15. #45
    Registered User
    Join Date
    Sep 2002
    Posts
    417
    lol... let me try writing a simple function.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. HELP!!!!emergency Problem~expert please help
    By unknowppl in forum C++ Programming
    Replies: 9
    Last Post: 08-21-2008, 06:41 PM
  2. HELP!!!!emergency ~expert please help
    By unknowppl in forum C Programming
    Replies: 1
    Last Post: 08-19-2008, 07:35 AM
  3. Replies: 10
    Last Post: 07-10-2008, 03:45 PM
  4. Reading/Writing in Binary
    By kuphryn in forum C++ Programming
    Replies: 4
    Last Post: 12-11-2001, 10:32 PM
  5. inserting characters into a binary tree
    By sballew in forum C Programming
    Replies: 4
    Last Post: 12-06-2001, 04:08 PM