13 Replies Latest reply: Feb 27, 2008 12:22 PM by YoungWinston RSS

    how the bit operations work in this example...

    807603
      Hi Gurus,
      I downloaded this program from forum to convert the byte[] to hex strings, but no idea how does it work!!!
      If you please take a exmple value and tell me exactly how that value is converted to hex string, i would greatly appreciate it.
      thanks,
          public String toHexString ( byte[] b )
          {
              StringBuffer sb = new StringBuffer( b.length * 2 );
              for ( int i=0; i<b.length; i++ )
              {
                  // look up high nibble char
                  sb.append( hexChar [( b[i] & 0xf0 ) >>> 4] );
      
                  // look up low nibble char
                  sb.append( hexChar [b[i] & 0x0f] );
              }
              String hStr = sb.toString();
              return Pattern.compile("0+").matcher(hStr).matches()?"":hStr;
          }
        • 1. Re: how the bit operations work in this example...
          796440
          Which specific lines do you not understand?
          • 2. Re: how the bit operations work in this example...
            807603
            If you please take a exmple value and tell me exactly how that value is converted to hex string, i would greatly appreciate it.
            Better yet, tell us what part you don't understand so we may refer you to the appropriate reference material.

            ~
            • 3. Re: how the bit operations work in this example...
              807603
              Steve, are you finding the forums particularly slow today? I had to abandon jverd in favor of Lorraine.
              • 4. Re: how the bit operations work in this example...
                807603
                Steve, are you finding the forums particularly slow today?
                Just the "Java Programming" forum, which is pretty typical as of late.

                ~
                • 5. Re: how the bit operations work in this example...
                  807603
                  private char[] hexChar = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
                  .
                  .
                  
                              // look up high nibble char
                              sb.append( hexChar [( b[i] & 0xf0 ) >>> 4] );
                   
                              // look up low nibble char
                              sb.append( hexChar [b[i] & 0x0f] );
                  this is the main part, bit operations to get hex characters, i dont understand...sorry didnt include the hexChar part in msg.

                  thanks
                  • 6. Re: how the bit operations work in this example...
                    YoungWinston
                    javalover2002 wrote:
                    Hi Gurus,
                    I downloaded this program from forum to convert the byte[] to hex strings, but no idea how does it work!!!
                    If you please take a exmple value and tell me exactly how that value is converted to hex string, i would greatly appreciate it.
                    thanks,
                    public String toHexString ( byte[] b )
                    {
                    StringBuffer sb = new StringBuffer( b.length * 2 );
                    for ( int i=0; i<b.length; i++ )
                    {
                    // look up high nibble char
                    sb.append( hexChar [( b[i] & 0xf0 ) >>> 4] );
                    
                    // look up low nibble char
                    sb.append( hexChar [b[i] & 0x0f] );
                    }
                    String hStr = sb.toString();
                    return Pattern.compile("0+").matcher(hStr).matches()?"":hStr;
                    }
                    OK, I'll have a stab:

                    1. A byte is 8 bits long, and made up of 2 hexadecimal digits, each of 4 bits (0-15).

                    2. The '&' operator performs a bitwise AND of two fields. Anything ANDed with '0' is always 0; anything ANDed with 1 is itself.

                    3. The real 'worker' bits of the code are "*( b\[i\] & 0xf0 ) >>> 4*" and "*b\[i\] & 0x0f*".
                    Lets take the first:
                    0xf0 == '11110000' in bit terms, so if you AND it with a byte (eg '01010101'), the result is '01010000';
                    that is then right-shifted by 4, resulting in '00000101' (ie, the contents of the 1st 4 bits).
                    That value is then used to find a character in an array called hexChar (which probably contains the characters '0' - '9', followed by 'A' - 'F').
                    Now the second one:
                    0x0f == '00001111' in bit terms, so if you AND it with '01010101', the result is '00000101';
                    no right shift required this time, you have the value of the last 4 bits.

                    4. Not quite sure what the rest of it does. Not familiar with the Pattern class.
                    • 7. Re: how the bit operations work in this example...
                      807603
                      javalover2002 wrote:
                      private char[] hexChar = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
                      .
                      .
                      
                      // look up high nibble char
                      sb.append( hexChar [( b[i] & 0xf0 ) >>> 4] );
                      
                      // look up low nibble char
                      sb.append( hexChar [b[i] & 0x0f] );
                      this is the main part, bit operations to get hex characters, i dont understand...sorry didnt include the hexChar part in msg.

                      thanks
                      Do you not understand what the private char[] hexChar = line does?

                      Do you not understand sb.append()?

                      Do you not understnad bitwise &?

                      Do you not understand what >>> does?

                      Do you not understnad something else?

                      It's to your benefit to be as precise and thorough as possible about what you're having trouble with.
                      • 8. Re: how the bit operations work in this example...
                        807603
                        younwinston, thanks for explanation. so eg if there is a character "A" how would get converted exactly to its hex? why

                        hexChar [( b[i] & 0xf0 ) >>> 4] and
                        hexChar [b[i] & 0x0f]
                        are using eg 0xf0 and 0x0f.
                        so how would a byte which has eg "A" will get converted to its value of hex? and what exactly >>> is being used for...kinda step by step explanation would realy be greatful.


                        vanilla_lorax. I mentioned many times above i dont understand the hex conversion using "bit operations".
                        • 9. Re: how the bit operations work in this example...
                          807603
                          I see. I guess because of the other stuff you said, it wasn't clear to me that it was the >>> in particular that you didn't understand.
                          • 10. Re: how the bit operations work in this example...
                            807603
                            are using eg 0xf0 and 0x0f.
                            Those are used as four-bit masks, one for the high-order bits of a byte, and one for the low-order.
                            how would a byte which has eg "A"
                            Please explain what you mean by that. I think your difficulty in understanding the code has to do with some fundamental misunderstanding of what a byte[] is, what a byte value is, and what hexadecimal notation is. That's not intended to be an insult; you're just using terminology that indicates you're not yet familiar with any of the material.
                            what exactly >>> is being used for...
                            The ">>>" operator is an unsigned right-shift operator. Have a look at this: http://www.javaranch.com/campfire/StoryBits.jsp

                            ~
                            • 11. Re: how the bit operations work in this example...
                              YoungWinston
                              javalover2002 wrote:
                              younwinston, thanks for explanation. so eg if there is a character "A" how would get converted exactly to its hex? why

                              hexChar \[( b\[i\] & 0xf0 ) >>> 4\] and
                              hexChar \[b\[i\] & 0x0f\]
                              are using eg 0xf0 and 0x0f.
                              so how would a byte which has eg "A" will get converted to its value of hex? and what exactly >>> is being used for...kinda step by step explanation would realy be greatful.


                              vanilla_lorax. I mentioned many times above i dont understand the hex conversion using "bit operations".
                              The operations I described above work the same regardless of value. What they do is mask out the 4 bits that you aren't interested in.
                              For your example, the character "A" is hex 41 or "01000001", so the first operation gives you
                              "A" & 0xf0, which == "01000000"
                              "01000000" >>> 4, which == "00000100" == 4
                              and hexChar[4] = "4"
                              The 2nd operation gives you
                              "A" & 0x0f, which == "00000001" == 1
                              and hexChar[1] = "1"

                              so it should print out "41".
                              • 12. Re: how the bit operations work in this example...
                                807603
                                thanks vanilla, yawn and youngwinston, all for your help

                                yawn that site is pretty decent.

                                younwinston, your explanation was perfect for me,

                                if i can ask even more detailed answer for myself, so... A is 01000001, and we used to '&' to 0xf0 to get 1 if both corresponding positions are 1, then shifted 4 positions to right side...then again used '&' with 0x0f to get same result but from the different position of the character...
                                sorry for the dumb question but question is Why?....why we had to do it in such particular way, ie use 0xf0 and shift it and then use 0x0f, and what '0xf0'/0x0f' represents?
                                • 13. Re: how the bit operations work in this example...
                                  807603
                                  javalover2002 wrote:
                                  sorry for the dumb question but question is Why?....why we had to do it in such particular way, ie use 0xf0 and shift it and then use 0x0f, and what '0xf0'/0x0f' represents?
                                  0xf0 is 11110000 in binary
                                  0x0f is 00001111 in binary
                                  When used with the & operator, it acts as a bit mask (masking out positions set to 0, and preserving positions set to 1).

                                  There is actually no reason to use both masks, only 0x0f is needed. This can be done by shifting first, then masking. If you have a byte with the bit representation "aaaabbbb", and you need the "aaaa" part, you can shift right 4 bits, resulting in "0000aaaa", and then mask (which may or may not be necessary, depending on the data type).