• Me (unregistered)

    I just cannot unsee it!

  • (cs)

    Duh. Not only is counting done from 1 to 4, it also starts on the wrong end of the nibble. Not bad. :)

  • IgglePiggle (unregistered)

    Oh sweet Mother of God!

  • Deze (unregistered)

    My eyes!

  • (cs)
    public static string ConvertToHexadecimal(string input)
    {
        byte[] bytes = Encoding.ASCII.GetBytes(input);
        StringBuilder s = new StringBuilder();
        for (int n = 0; n < bytes.Length; n++) {
            s.Append(String.Format("{0,2:x}", bytes[n]).Replace(" ", "0"));
        }
        return s.ToString();
    }

    Well that would be my implementation. Probably a better /shorter way somewhere.

  • (cs)

    This guy was obviously paid by the line. Laugh all you want, but he's now sipping martinis on his private 100m yacht.

  • (cs)

    Dear sir, we are interested in your implementation of this function. We find it to be sufficiently complex for use in our enterprise software, as we find that all functions under 1000 lines are inadequate and poor. Please expand on your comments somewhat, and we would be willing to pay the going market rate for this product ($200/LOC).

    Yours sincerely,

    PHB

  • evir doh cysp (unregistered)

    hello freind

    i am try ot hex some String for collage. but you Jaava is not work. ther is nto complier erorr.

    how to mak wrok?

    emial of list plz?

  • (cs) in reply to Sunday Ironfoot
    Sunday Ironfoot:

    Well that would be my implementation. Probably a better /shorter way somewhere.

    What about Integer.toHexString() ?

  • Mog (unregistered) in reply to Sunday Ironfoot

    Well, I dunno much about java, but C... *("0123456789ABCDEF" + ((bit1 << 3) | (bit2 << 2) | (bit3 << 1) | bit4)) should work...

    But at least their version is easier to extend if hexadecimal suddenly gets a 17th character...

  • Stavros (unregistered)

    No fewer than!

  • Gruff (unregistered)

    So THAT'S why my Vista runs so slow...

  • Bisqwit (unregistered) in reply to Mog
    Well, I dunno much about java, but C... *("0123456789ABCDEF" + ((bit1 << 3) | (bit2 << 2) | (bit3 << 1) | bit4)) should work...
    I like "0123456789ABCDEF"[bit1*8+bit2*4+bit3*2+bit4] slightly better.
  • blub (unregistered) in reply to Bisqwit
    Bisqwit:
    Well, I dunno much about java, but C... *("0123456789ABCDEF" + ((bit1 << 3) | (bit2 << 2) | (bit3 << 1) | bit4)) should work...
    I like "0123456789ABCDEF"[bit1*8+bit2*4+bit3*2+bit4] slightly better.

    I don't know much C but I love this solution :)

  • (cs) in reply to Bisqwit
    var idx = 0001 * (bit1 ? 1 : 0)
            + 0010 * (bit2 ? 1 : 0)
            + 0100 * (bit3 ? 1 : 0)
            + 01000 * (bit4 ? 1 : 0);
    
    switch(idx){
    case 0:
       return "0";
    case 1:
       return "1";
    case 2:
       return "2";
    //...
    case 16:
       return "F";
    }
  • SlyEcho (unregistered) in reply to Sunday Ironfoot
    Sunday Ironfoot:
    public static string ConvertToHexadecimal(string input)
    {
        byte[] bytes = Encoding.ASCII.GetBytes(input);
        StringBuilder s = new StringBuilder();
        for (int n = 0; n < bytes.Length; n++) {
            s.Append(String.Format("{0,2:x}", bytes[n]).Replace(" ", "0"));
        }
        return s.ToString();
    }

    Well that would be my implementation. Probably a better /shorter way somewhere.

    public static string ConvertToHexadecimal(string input)
    {
        return ConvertToHexadecimal(Encoding.Default.GetBytes(input));
    }
    public static string ConvertToHexadecimal(byte[] input)
    {
        return ConvertToHexadecimal(input, 0, input.Length);
    }
    public static string ConvertToHexadecimal(byte[] input, int index, int length)
    {
        const string hex = "0123456789abcdef";
        char[] buffer = new char[length * 2];
        for (int n = index; n < length; n++) {
            buffer[2*n] = hex[input[n] >> 4];
            buffer[2*n+1] = hex[input[n] & 0x0f];
        }
        return new string(buffer);
    }

    A slightly better version would be one that works with Streams and TextWriters.

  • NiceWTF (unregistered) in reply to Sunday Ironfoot
    Sunday Ironfoot:
    [..] Well that would be my implementation. Probably a better /shorter way somewhere.

    In Java it can indeed be done in 1 line:

    public static String toHex(byte[] input) {
      return new BigInteger(input).toString(16); 
    }
    
  • csrster (unregistered)

    We had a related wtf here a couple of weeks ago. On my current project, we use BigInteger to do this conversion:

    new BigInteger(1, data).toString(16);

    which should be fine. Except that our byte-arrays actually represent sha1 hashcodes. We spent a long time scratching our hands over strange checksum mismatches in the code, until it finally came to our attention that the problem only arose when the checksum had leading 0's .

  • (cs)

    Wow, I've written it more concisely in XSL (version 1)

  • (cs) in reply to Zecc
    Zecc:
    var idx = 0001 * (bit1 ? 1 : 0)
            + 0010 * (bit2 ? 1 : 0)
            + 0100 * (bit3 ? 1 : 0)
            + 01000 * (bit4 ? 1 : 0);
    
    That would be octal.
  • Anonymous (unregistered)

    Python:

    'data as bytestring'.encode('hex')
  • myself (unregistered)

    In C:

    what about a good old sprintf?

  • Marcelk (unregistered) in reply to Bisqwit
    Well, I dunno much about java, but C... *("0123456789ABCDEF" + ((bit1 << 3) | (bit2 << 2) | (bit3 << 1) | bit4)) should work...
    I like "0123456789ABCDEF"[bit1*8+bit2*4+bit3*2+bit4] slightly better.

    In C, such should always be written as (bit18+bit24+bit3*2+bit4)["0123456789ABCDEF"]

  • Me (unregistered) in reply to Marcelk
    Marcelk:
    Well, I dunno much about java, but C... *("0123456789ABCDEF" + ((bit1 << 3) | (bit2 << 2) | (bit3 << 1) | bit4)) should work...
    I like "0123456789ABCDEF"[bit1*8+bit2*4+bit3*2+bit4] slightly better.

    In C, such should always be written as (bit18+bit24+bit3*2+bit4)["0123456789ABCDEF"]

    That's just fugly.

  • (cs) in reply to Stavros
    Stavros:
    No fewer than!
    Wanna bet‽

    Linguists say no! Or actually, they say "prescriptivist poppycock", but it's much the same thing.

  • (cs) in reply to Mog
    But at least *their* version is easier to extend if hexadecimal suddenly gets a 17th character...
    Exactly. I find especially enlightened this part of the code:
    public static final int NUMBER_OF_HEXADECIMAL_CHARACTERS_PER_BYTE = 2;
    to ensure compatibility, should the Universe reboot and the laws of mathematics be modified, in case the number of hex numbers per byte changes.
  • Not Dorothy (unregistered) in reply to D0R
    D0R:
    Exactly. I find especially enlightened this part of the code:
    public static final int NUMBER_OF_HEXADECIMAL_CHARACTERS_PER_BYTE = 2;
    to ensure compatibility, should the Universe reboot and the laws of mathematics be modified, in case the number of hex numbers per byte changes.

    Pah, who says that the numbers of bits in a byte will be an integer value after the reboot. Put everything in strings and decode it as required.

  • (cs) in reply to D0R
    D0R:
    But at least *their* version is easier to extend if hexadecimal suddenly gets a 17th character...
    Exactly. I find especially enlightened this part of the code:
    public static final int NUMBER_OF_HEXADECIMAL_CHARACTERS_PER_BYTE = 2;
    to ensure compatibility, should the Universe reboot and the laws of mathematics be modified, in case the number of hex numbers per byte changes.
    Actually, in C a byte does not necessarily have 8 bits. There is nothing in the least unusual about needing more than 2 hex digits to represent a byte.
  • srednitsa (unregistered) in reply to brazzy

    In Java, a byte does have 8 bits.

  • (cs) in reply to srednitsa
    srednitsa:
    In Java, a byte does have 8 bits.
    Yes. It would thus require a change of the Java standard - not quite as epochal as a "Universe reboot", wouldn't you agree?
  • JimBob (unregistered) in reply to Bisqwit
    Bisqwit:
    Well, I dunno much about java, but C... *("0123456789ABCDEF" + ((bit1 << 3) | (bit2 << 2) | (bit3 << 1) | bit4)) should work...
    I like "0123456789ABCDEF"[bit1*8+bit2*4+bit3*2+bit4] slightly better.
    Like it all you want, but all it'll get you is a core dump ;)
  • Me (unregistered)

    That's so obviously wrong! The arrays are never used!

    A proper implementation should be: public static final object[] F_BITS = new object[]{true, true, true, true, F, F_LOWER};

    and then they can do the check by simply doing: if (bit1 == F_BITS[FIRST_BIT_OFFSET] && bit2 == F_BITS[SECOND_BIT_OFFSET] && bit3 == F_BITS[THIRD_BIT_OFFSET] && bit4 == F_BITS[FOURTH_BIT_OFFSET]) return F_BITS[LOWERCASE_OFFSET];

    (They need to add constants for LOWERCASE_OFFSET and UPPERCASE_OFFSET and use the same number constant for both from 0 to 9).

    for each letter in the array. There, much better.

  • Rob (unregistered) in reply to Dalden
    Dalden:
    Sunday Ironfoot:

    Well that would be my implementation. Probably a better /shorter way somewhere.

    What about Integer.toHexString() ?

    or hex = sprintf(i, '%x'); // not sure on the java syntax

  • (cs) in reply to Bisqwit
    Bisqwit:
    Well, I dunno much about java, but C... *("0123456789ABCDEF" + ((bit1 << 3) | (bit2 << 2) | (bit3 << 1) | bit4)) should work...
    I like "0123456789ABCDEF"[bit1*8+bit2*4+bit3*2+bit4] slightly better.

    Shift and OR operations are faster than multiplication. I'd be curious to compare the assembly output from an optimizing compiler for each and see which is more efficient.

  • Leon (unregistered) in reply to ambrosen
    ambrosen:
    Stavros:
    No fewer than!
    Wanna bet‽

    Linguists say no! Or actually, they say "prescriptivist poppycock", but it's much the same thing.

    Yakka foob mog, grub pubbawup zink watoom gazork. Chumble spuzz.

    And if you don't like those words, you're being prescriptivist. I think they're perfectly valid.

  • Roman (unregistered)

    Perl code examples plz? ;-)

  • Jens Kleemann (unregistered) in reply to emddudley

    a (good) optimizing compiler will most definitely transform the "bit1*8" to "bit1<<3" as long as bit1 .. bitn are integer/byte/... types

    btw. see also this (i love this example - code like that has driven me nuts on "reengineering" ) http://www.nynaeve.net/?p=115

  • (cs) in reply to Leon
    Leon:
    ambrosen:
    Stavros:
    No fewer than!
    Wanna bet‽

    Linguists say no! Or actually, they say "prescriptivist poppycock", but it's much the same thing.

    Yakka foob mog, grub pubbawup zink watoom gazork. Chumble spuzz.

    And if you don't like those words, you're being prescriptivist. I think they're perfectly valid.

    Indeed, quite cromulent.

  • frustrati (unregistered) in reply to brazzy
    brazzy:
    Actually, in C a byte does not necessarily have 8 bits. There is nothing in the least unusual about needing more than 2 hex digits to represent a byte.
    Actually, in C there is no "byte" data type
  • (cs)

    They use not only too many lines to do a simple things that could be done in one line, but they have way too many comments, also!

  • (cs) in reply to Roman
    Roman:
    Perl code examples plz? ;-)
    sprintf("%x",$_);

    ?

  • YAFIYGI (unregistered) in reply to frustrati
    frustrati:
    brazzy:
    Actually, in C a byte does not necessarily have 8 bits. There is nothing in the least unusual about needing more than 2 hex digits to represent a byte.
    Actually, in C there is no "byte" data type
    Actually, brazzy did not write anything about data types. TRWTF: Trying to be a smart butt + lacking knowledge. Hint: Read the standard before posting nonsense about C.
  • (cs) in reply to csrster
    csrster:
    We had a related wtf here a couple of weeks ago. On my current project, we use BigInteger to do this conversion:

    new BigInteger(1, data).toString(16);

    which should be fine. Except that our byte-arrays actually represent sha1 hashcodes. We spent a long time scratching our hands over strange checksum mismatches in the code, until it finally came to our attention that the problem only arose when the checksum had leading 0's .

    Working for Nintendo?

  • (cs)

    One day, after a code review by one of our 'senior' developers this little beauty showed up...

    #define NUMBER_OF_BITS_IN_BYTE 8

    The justification was... that the byte might change.... and no 'magic' numbers should appear in the code...

  • Ayin (unregistered) in reply to emddudley

    Not necessarily, depends on the platform. Some platforms only have 1-bit shift operations, and on those platforms, bit1<<3 would need a loop to be implemented, which may be slower than a multiplication.

    Anyway, good optimizers always decide, on a case-per-case basis, which one is faster, so programmers should just stick to what is more readable (do you actually want to multiply values, or just shift bits?).

    Never try to do the optimizer's work manually!

  • Nobody (unregistered) in reply to Manos
    Manos:
    One day, after a code review by one of our 'senior' developers this little beauty showed up...

    #define NUMBER_OF_BITS_IN_BYTE 8

    The justification was... that the byte might change.... and no 'magic' numbers should appear in the code...

    Actually I can understand this. Not because the byte might change but rather to document the code. Why make the next guy who has to maintain your code have to figure out what the number 8 represents when you can make it glaringly obvious this way?

  • Geek (unregistered)

    I'm sure the code making use of this depends on a certain bug in this "algorithm", so you won't be able to exchange it.

  • (cs) in reply to Manos
    Manos:
    One day, after a code review by one of our 'senior' developers this little beauty showed up...

    #define NUMBER_OF_BITS_IN_BYTE 8

    The justification was... that the byte might change....

    You might want to read up on what a "byte" is and is not: http://en.wikipedia.org/wiki/Byte The only WTF in that is that he didn't use CHAR_BIT in limits.h, which has exactly that content for exactly that reason.

  • (cs)

    From: Management To: Code Monkey Date: Friday, August 29, 2008 04:15 pm Subject: Labor Day Holiday

    Mr. Mankey,

    I have received your request for time off on Monday. This will be no problem as long as you finish the hexadecimal conversion method assigned to you earlier this month. It is looking good so far, but the client has requested a small piece of additional functionality. Please upgrade your method to allow balanced ternary input and provide the option for base 42 output. This should be an easy fix for an experienced programmer. Remember, the new method must be released to production by the end of the day.

    Regards,

    P. H. Boss

  • (cs) in reply to Marcelk
    Marcelk:
    I like "0123456789ABCDEF"[bit1*8+bit2*4+bit3*2+bit4] slightly better.
    In C, such should always be written as (bit1*8+bit2*4+bit3*2+bit4)["0123456789ABCDEF"]

    This one is cleaner: (bit18 + bit24 + bit32 + bit4 + "0123456789ABCDEF")

Leave a comment on “Classic WTF: To the Hexth Degree”

Log In or post as a guest

Replying to comment #215188:

« Return to Article