Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C++ (http://www.programmingforums.org/forum15.html)
-   -   Binary/Hex Text Encoder/Decoder (http://www.programmingforums.org/showthread.php?t=14348)

Baphomet Nov 6th, 2007 12:03 PM

Binary/Hex Text Encoder/Decoder
 
I am making a hexidecimal/binary text converter. It takes text and converts it to and from hex and to from binary. It is created in wxWidgets. I have the text conversion part done. What I need is the opposite. I have no idea how to go about this. if anyone has an easy algorithm, could they post it. Thanks in advance.

If you are still unsure of what the project is, look here its similar to this except a GUI app programmed in C++.

DaWei Nov 6th, 2007 12:21 PM

Re: Binary/Hex Text Encoder/Decoder
 
Everything in the computer is binary. Text is merely a predefined interpretation of binary values. Numbers are merely another, different interpretation of the same binary values. Numbers are presented to the viewer, typically, as text. Thus, the display value for one (1) is not the value, 1, but the value (in ASCII) 0x31 ('1').

Note that I mention ASCII (ANSI). This is for good reason. The link you provide says that the hex value of "ABC" is 41 42 43. This is only true if the text is encoded using that particular (ANSI) set of rules. It can be totally different when using another set of rules (unicode, ebcdic, other wide-character formats). For instance, in one version of ebcdic, "ABC" is hex C1 C2 C3.

You are going to have to address that issue, even if you merely declare that you're using an ANSI table, so users shouldn't call the hot line if they happen to disagree.

At any rate, you need to be more specific with your question, and it would be a good idea to toss up some code that you think should handle the conversions appropriately.

You might also want to search the forum and the web.

Narue Nov 6th, 2007 12:29 PM

Re: Binary/Hex Text Encoder/Decoder
 
Just for grins:
:

  1. #include <bitset>
  2. #include <iostream>
  3. #include <limits>
  4. #include <sstream>
  5. #include <string>
  6.  
  7. std::string to_binary ( const std::string& src )
  8. {
  9.   const int bits = std::numeric_limits<unsigned char>::digits;
  10.  
  11.   std::string ret;
  12.  
  13.   for ( std::string::size_type i = 0; i < src.size(); i++ ) {
  14.     ret += std::bitset<bits> ( src[i] ).to_string();
  15.  
  16.     if ( i < src.size() - 1 )
  17.       ret += ' ';
  18.   }
  19.  
  20.   return ret;
  21. }
  22.  
  23. std::string from_binary ( const std::string& src )
  24. {
  25.   const int bits = std::numeric_limits<unsigned char>::digits;
  26.  
  27.   std::stringstream in ( src );
  28.   std::string byte;
  29.   std::string ret;
  30.  
  31.   while ( in>> byte )
  32.     ret += char ( std::bitset<bits> ( byte ).to_ulong() );
  33.  
  34.   return ret;
  35. }
  36.  
  37. std::string to_hex ( const std::string& src )
  38. {
  39.   std::stringstream out;
  40.  
  41.   for ( std::string::size_type i = 0; i < src.size(); i++ ) {
  42.     out<< std::hex << int ( src[i] );
  43.  
  44.     if ( i < src.size() - 1 )
  45.       out<<' ';
  46.   }
  47.  
  48.   return out.str();
  49. }
  50.  
  51. std::string from_hex ( const std::string& src )
  52. {
  53.   std::stringstream in ( src );
  54.   std::string ret;
  55.   int byte;
  56.  
  57.   while ( in>> std::hex >> byte )
  58.     ret += char ( byte );
  59.  
  60.   return ret;
  61. }
  62.  
  63. int main()
  64. {
  65.   std::cout<< to_binary ( "test" ) <<'\n';
  66.   std::cout<< from_binary ( to_binary ( "test" ) ) <<'\n';
  67.   std::cout<< to_hex ( "test" ) <<'\n';
  68.   std::cout<< from_hex ( to_hex ( "test" ) ) <<'\n';
  69. }


Baphomet Nov 6th, 2007 2:28 PM

Re: Binary/Hex Text Encoder/Decoder
 
Quote:

Everything in the computer is binary. Text is merely a predefined interpretation of binary values. Numbers are merely another, different interpretation of the same binary values. Numbers are presented to the viewer, typically, as text. Thus, the display value for one (1) is not the value, 1, but the value (in ASCII) 0x31 ('1').

Note that I mention ASCII (ANSI). This is for good reason. The link you provide says that the hex value of "ABC" is 41 42 43. This is only true if the text is encoded using that particular (ANSI) set of rules. It can be totally different when using another set of rules (unicode, ebcdic, other wide-character formats). For instance, in one version of ebcdic, "ABC" is hex C1 C2 C3.
It would be really sad if I did not know this. Spare me a lecture on the basics of ASCII text encoding. I already have the ability to convert Text to Hex and Binary. What I need to do is take binary or hex (shown as a ascii string) and convert it to text. For example, if some enters 54 65 78 74, I want the program to convert that to the text equivalent in ASCII: "Text". I hate unicode, and have gotten around getting the unicode version of things. I just have to use a standard C char for conversion. Its easy enough.
Maybe I should post what I have so far, if you want this, I'll have to cleean up my code. I don't code with other people in mind.

DaWei Nov 6th, 2007 2:36 PM

Re: Binary/Hex Text Encoder/Decoder
 
It did seem sad that you didn't appear to recognize that basic fact, but it's a quite common failing. Your post gave no indication that you understood that. As a matter of fact, you said you had no idea how to go about it. That implies that you're confused.

Perhaps if you had posted some code, as I suggested, it would have been clearer that you understand more than appeared to be the case.

When you come here for help or evaluation, you can reasonably expect that most critiques will be on the negative side. You're looking to have deficiencies pointed out. That's the point.

Very few people come and post and ask to be lauded for their skill and slickness. Let me suggest that you read Eric Raymond's "Smart Questions". There's a link in the introduction to the rules.

If you can't deal with things such as you encountered in my post (which was in no way hateful), perhaps you should return to the playground until you grow up.

Baphomet Nov 6th, 2007 2:49 PM

Re: Binary/Hex Text Encoder/Decoder
 
No, I'm not offended. Its my fault. You had no way of knowing how to answer my question with how I asked it. I'm not good at expressing... anything. I'll grab my crude code example here, tell me if you need it cleaned up (more comments). This is what I have. Keep in mind this code works fine.

:

/*
 * MakeHexClick when user wants text converted to ASCII hex code
 */
void Hex_Binary_ConverterDlg::MakeHexClick(wxCommandEvent& event)
{
        wxString TextCon,CharBuf,Output="",Toss; //Text to be converted,Single char holder,
    char t[2]; //temp c char
    //Output text,Garbage
    TextCon=HTextIn->GetValue(); //Get User Input so we can convert
    int max=TextCon.Len(); //end char and current char in conversion
    //convert text
    for(int curr=0;curr<max;curr++)
        {
      CharBuf=TextCon.Mid(curr,1); //Get 1 char
      strcpy(t,CharBuf.c_str()); //make sure its ascii
      Toss.sprintf("%02X ",t[0]);
      Output.Append(Toss);//Make it a Hex Digit
    }
    HTextOut->SetValue(Output);
}

/*
 * MakeBinClick when user clicks binary convert button
 */
void Hex_Binary_ConverterDlg::MakeBinClick(wxCommandEvent& event)
{
        wxString TextCon,CharBuf,Output="",Binary="00000000 "; //Text to be converted,Single char holder,
    char t[2]; //temp c char
    //Output text,Garbage
    TextCon=BTextIn->GetValue(); //Get User Input so we can convert
    int max=TextCon.Len(); //end char and current char in conversion
    //convert text
    for(int curr=0;curr<max;curr++)
        {
      CharBuf=TextCon.Mid(curr,1); //Get 1 char
      strcpy(t,CharBuf.c_str()); //make sure its ascii
      int num=(int)t[0];
      Binary="00000000 ";
      while(num!=0)
      {
        if(num>=128)
        {
          Binary[0]='1';
          num=num-128;
        }
        else if(num>=64)
        {
          Binary[1]='1';
          num=num-64;
        }
        else if(num>=32)
        {
          Binary[2]='1';
          num=num-32;
        }
        else if(num>=16)
        {
          Binary[3]='1';
          num=num-16;
        }
        else if(num>=8)
        {
          Binary[4]='1';
          num=num-8;
        }
        else if(num>=4)
        {
          Binary[5]='1';
          num=num-4;
        }
        else if(num>=2)
        {
          Binary[6]='1';
          num=num-2;
        }
        else if(num>=1)
        {
          Binary[7]='1';
          num=num-1;
        }
    }
      Output.Append(Binary);
    }
    BTextOut->SetValue(Output);
}


lectricpharaoh Nov 6th, 2007 8:58 PM

Re: Binary/Hex Text Encoder/Decoder
 
Quote:

Originally Posted by Baphomet
I don't code with other people in mind.

This isn't too reassuring. :/

On another note, your line that reads Binary="00000000 "; may cause problems. Many (most?) modern compilers alias strings to save space; if you have two string literals that contain the same thing, the compiler may create a single string, and point both pointers to it. You'd be better off creating an actual array of char: Binary[8] = {'0', '0', '0', '0', '0', '0', '0', '0'}; Another issue is string literals may be placed in a read-only section of memory (the code segment, for example), and writing to them can cause undefined behavior (often a segmentation fault).

Baphomet Nov 7th, 2007 10:38 AM

Re: Binary/Hex Text Encoder/Decoder
 
It does not cause problems with the compiler I use. The script above works perfectly. I don't give a shit about what other compilers do. Besides thats a wxString. Its not the same as standard C++ string or a C character array. Compile the above script with gcc and it works fine. Its been proven with my program. Besides, it won't matter if it alies the string because I won't make an identicle one.

DaWei Nov 7th, 2007 10:42 AM

Re: Binary/Hex Text Encoder/Decoder
 
Baphomet, let me ask you this: if you're not interested in professional answers, discard them out of hand, and bitch about receiving them, why the hell are you posting here?

Write your questions in notepad and send them to /dev/null. You won't be bothered with answers you don't like.

Baphomet Nov 7th, 2007 4:29 PM

Re: Binary/Hex Text Encoder/Decoder
 
I am interested in professional answers. I'd be glad to accept one as soon as I actually see one posted here. I have come up with an idea for my algorithm. Let me know what you think of it. Give me a serious response and I won't bitch.

For hex:
1.) Eliminate whitespace characters (newlines, spaces, ect.)
2.) Multiply the first digit by 16 and make equivalents for A,B,C,D,E.F and lowercase a,b,c,d,e,f
3.) add the second digit and again make for letters A,B, and so on.
4.)Make int into a character using cast operator and append it to the string
5.)Repeat for each char until finished


For binary:
1.) remove whitespace characters
2.)Multiply each bit by its corresponding value
3.) cast the int and append to the output string
4.)Repeat for each char


All times are GMT -5. The time now is 3:25 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC