2

I am struggling trying to convert a hex number string back to the original string. I convert the string using the following method:

 private static String hex(String  binStr) {

        String newStr = new String();

        try {
            String hexStr = "0123456789ABCDEF";
            byte [] p = binStr.getBytes();
            for(int k=0; k < p.length; k++ ){
                int j = ( p[k] >> 4 )&0xF;
                newStr = newStr + hexStr.charAt( j );
                j = p[k]&0xF;
                newStr = newStr + hexStr.charAt( j ) + " ";
            }   
        } catch (Exception e) {
            System.out.println("Failed to convert into hex values: " + e);
        } 

        return newStr;
    }

I am really stuck, and any advice would be greatly appreciated.

Thank you in advance

1
  • 4
    Could you give sample input and the expected output? Commented Nov 18, 2012 at 17:48

2 Answers 2

1

Consider this:

     String hexStr = "0123456789ABCDEF";
     long i = Long.valueOf(hexStr, 16);
     System.out.println(Long.toHexString(i));
Sign up to request clarification or add additional context in comments.

Comments

1

The code in the question destroys information. Only the most significant two bits and the least significant four bits of each input byte contribute to the result. That means it cannot, in general, be reversed.

If the right shift had been by four bits, instead of 6:

int j = ( p[k] >> 4 )&0xF;

all the input would have been preserved, and the original string could have been recovered from the hex string. Maybe you really meant the four bit shift?

2 Comments

Yes sorry, I did indeed mean 4 bits; >> 4
Which version did you actually use to generate the string you are trying to convert back?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.