CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 9 of 9
  1. #1

    Help Understanding a piece of Code

    There is this neat piece of code on the next for converting a decimal value into hex, I can't quite figure out how it works, I was wondering if anyone could help.

    Code:
    #include <iostream>
    using namespace std;
    
    int main() {
        int n;
        while (cin >> n) {
            cout << "decimal: " << n << endl;
          
    
             cout << "size of int: " << sizeof(int) << endl;
    
            //--- Print hex with leading zeros
            cout << "hex    : ";
            for (int i=2*sizeof(int) - 1; i>=0; i--) {
                cout << "0123456789ABCDEF"[((n >> i*4) & 0xF)];
            }
            cout << endl << endl;
        }
    return 0;
    }
    My bitwise is a little flaky to say the least, but I'm eager to learn it. I was hoping some light shed on this might help me.

    The original source is Convert to Hex

  2. #2
    Join Date
    May 2007
    Location
    Scotland
    Posts
    1,164

    Re: Help Understanding a piece of Code

    Hi goatslayer. So as to not spoil your learning fun, here is a link to a nice bitwise operator explanation:

    http://www.phim.unibe.ch/comp_doc/c_...T/bitwise.html

    This should help you figure it out.

    Edit:

    Also here is a binary-hex conversion table:

    http://www.dewassoc.com/support/msdo...exadecimal.htm

    Ignore the '0x' in front of the hex numbers you compare to when using this table. For example 0xF is 'f' on the hex conversion table, and 0xFF is 'ff'.
    Last edited by PredicateNormative; December 6th, 2007 at 08:48 AM.

  3. #3
    Join Date
    Jul 2003
    Location
    Linköping, Sweden
    Posts
    261

    Re: Help Understanding a piece of Code

    Why not replace half of that code with this much simpler version?
    Code:
    cout << "hex   :" << hex << end;
    Errare humanum est, ergo non sum humanus.

  4. #4

    Re: Help Understanding a piece of Code

    Thanks PredicateNormative, I'll have a good look at that, I think the basics of the bitwise I have down so I might be back, as I think the main source of my problem is:

    "0123456789ABCDEF"[((n >> i*4) & 0xF)];

    Is that some sort of cast? with the hex characters first?

    Hnefi - I might not get the bitwise fully, but I believe this code allows you to store the value in the loop in a char array, or string or whatnot first. - cout << hex only formats on console output if I am not mistaken?

    And the alternative:

    itoa(int, string, base) - is non standard and not supported by all compilers.

    EDIT: the point being, much more useful.
    Last edited by goatslayer; December 6th, 2007 at 09:30 AM.

  5. #5
    Join Date
    Nov 2006
    Location
    Essen, Germany
    Posts
    1,344

    Re: Help Understanding a piece of Code

    Hint:
    There´s no cast involved, just a local anonymous char array.
    - Guido

  6. #6
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Help Understanding a piece of Code

    I think that expression is indexing into a literal string. I didn't know that was possible, but I suppose it would be.

  7. #7

    Re: Help Understanding a piece of Code

    GNiewerth, Lindley: Thank you. That along with PredicativeNormative's comments, should just about help me fill in the blanks if I'm not mistaken. Excellent work.

  8. #8
    Join Date
    Jan 2001
    Posts
    253

    Re: Help Understanding a piece of Code

    It is a little clearer if you change it to the following:

    Code:
    inline char HexDigit( int value )
    {
       return "0123456789ABCDEF"[value];
    }
    
    ...
    
    cout << HexDigit(((n >> i*4) & 0xF));
    Note that the pointer[index] in C++ is equivalent to *(pointer+index), so either of the following would also work:

    Code:
    inline char HexDigit( int value )
    {
       return value["0123456789ABCDEF"];
    }
    or

    Code:
    inline char HexDigit( int value )
    {
       return *("0123456789ABCDEF"+value);
    }

  9. #9
    Join Date
    May 2007
    Location
    Scotland
    Posts
    1,164

    Re: Help Understanding a piece of Code

    Quote Originally Posted by goatslayer
    Hnefi - I might not get the bitwise fully, but I believe this code allows you to store the value in the loop in a char array, or string or whatnot first. - cout << hex only formats on console output if I am not mistaken?
    Hnefi's solution is the simplest, and if you want to pipe the solution to a string first then you can slightly modify it to use ostringstream instead of cout:

    Code:
    #include <iostream>
    #include <string>
    #include <sstream>
    
    int main()
    {
      int num = 255;
      std::ostringstream os;
    
      //cout
      std::cout << std::hex << num << std::endl;
    
      //ostringstream equivalent
      os << std::hex << num << std::endl;
    
    
      std::string myString = os.str();
      std::cout << myString.c_str() << std::endl;
    }
    Last edited by PredicateNormative; December 6th, 2007 at 09:52 AM.

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

Featured