Link to home
Create AccountLog in
Avatar of tonelm54
tonelm54

asked on

Decode from Hex to String

I have been using the following function to decode a Hex to string:-
       function decodeFromHex(str) {
            var r = "";
            var e = str.length;
            var s;
            while (e >= 0) {
                s = e - 3;
                r = String.fromCharCode("0x" + str.substring(s, e)) + r;
                e = s;
            }
            return r;
        }


But when I run it with the hex code "4d61696e436f6e74656e745f74787455736572" I get '"M¿¿¿¿¿¿¿¿¿¿¿¿"' where it should be "Hello this is a test"

Its a logic error I know, but I need sleep and cant figure this out.

Any siggestions, sorry!
ASKER CERTIFIED SOLUTION
Avatar of ncoo
ncoo

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of tonelm54
tonelm54

ASKER

Your right, it should decode to that, thank you!

The issue I have is it works great, builds the string perfectly, until the last time it runs the while loop, where is resets r to "" so there is nothing to return
So the Hex string "4d61696e436f6e74656e745f74787455736572"

Up to the last time it runs the while loop r = "MainContent_txtUser"

The r = "" when it runs the line "return r;"
Figured it out, it was "while (e >= 0) {" which should be  "while (e > 0) {"

function decodeFromHex(str) {
            var r = "";
            var e = str.length;
            var s;
            while (e > 0) {
                s = e - 2;
                r = String.fromCharCode("0x" + str.substring(s, e)) + r;
                e = s;
            }
            return r;
        }
You should also investigate the "parseInt()" function - for converting between bases - as well as the "toString()" function.

Might save a bit of headache ;-)
SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account

I think #34462908 is a more definitive solution and of greater benefit to future viewers of the subject.
3) Split

Answers the question based on the users code: #34460962

Provides a totally different solution to the question: #34462908