views:

550

answers:

4

I have a H/W device that normally uses a serial port for an interface, sending and receiving binary messages to a PC UI program. I've added an Ethernet port and small TCP/IP stack with a small web server that I want to use to replace the serial port UI with a web browser UI.

The messages are mostly request/response sort of things, but for some web pages I may need to Tx/Rx two or more messages to get all the info I need for the page. I'll use the AJAX XMLHttpRequest() to send the messages and get the responses for a page.

The H/W device has limited resources (CPU & RAM) so to keep it simple on that end I want to just make a little CGI interface that takes outgoing messages and encodes them as HEX ASCII (i.e. two HEX ASCII chars/byte) to send to the browser which will use some java script to pick apart the messages into fields and convert them to numeric vars and display them to the user. Same for messages sent from the browser to the H/W device.

Messages contain a mixture of field types, signed & unsigned bytes, shorts, longs, floats, and are futher complicated by being mostly in little endian byte order in the messages.

I can handle the H/W end code, but I'm struggling to learn java script and could use help with a function to translate the HEX ASCII <-> numerics on the browser end.

Any ideas? Any example code some where?

Thanks, Paul

+6  A: 

Sounds like you want parseInt. It takes a string and an optional radix (which should always be supplied), and parses the number as an integer in that radix (or a radix based on the format of the number if none is supplied, which is why you should always supply one; people are surprised to find that parseInt("010") returns 8).

> parseInt("ab", 16)
171

To convert back to hex, you can use toString:

> var num = 16
> num.toString(16)
"10"

Note that you will have to pad it out to two characters yourself if it comes out as only a single character:

> num = 5
> num.toString(16)
"5"

I was bored, so I wrote some functions to do the conversion in both directions for you:

function parseHexString(str) { 
    var result = [];
    // Ignore any trailing single digit; I don't know what your needs
    // are for this case, so you may want to throw an error or convert
    // the lone digit depending on your needs.
    while (str.length >= 2) { 
        result.push(parseInt(str.substring(0, 2), 16));
        str = str.substring(2, str.length);
    }

    return result;
}

function createHexString(arr) {
    var result = "";
    for (i in arr) {
        var str = arr[i].toString(16);
        // Pad to two digits, truncate to last two if too long.  Again,
        // I'm not sure what your needs are for the case, you may want
        // to handle errors in some other way.
        str = str.length == 0 ? "00" :
              str.length == 1 ? "0" + str : 
              str.length == 2 ? str :
              str.substring(str.length-2, str.length);
        result += str;
    }

    return result;
}

Which can be used as follows:

> parseHexString("abcd100001")
[171, 205, 16, 0, 1]
> createHexString([0, 1, 2, 10, 20, 100, 200, 255, 1000, 2000])
"0001020a1464c8ffe8d0"
> parseHexString(createHexString([0, 1, 2, 10, 20, 100, 200, 255, 1000, 2000]))
[0, 1, 2, 10, 20, 100, 200, 255, 232, 208]
Brian Campbell
So using javascript, I would parse the ASCII HEX string as a char array converting every two chars into a two char string, then use parseInt() to convert it to a byte and put it into a byte array resulting in a byte array 1/2 the size of the ASCII HEX string?Then pick out the bytes from the byte array for each field, and handle the endian byte swapping (is there a function for that?)?And for messages going the other way, what's the javascript function for converting a byte to two ASCII HEX chars?BTW, much thanksPaul
Paul
That should help me get started. Much thanks. Now I just have to wrap some array handling around it and that should do it.Thanks again,Paul
Paul
A: 

You're looking for the parseInt() function:

x = "0xff";
y = parseInt(x, 16);
alert(y);   //255
J.J.
+1  A: 

did you looking for something like these 2 functions ?

<html>
    <head>
    <script type="text/javascript">
        function hex2Decimal( hex )
        {
            return parseInt("0x"+hex);
        }

        function decimal2Hex( num )
        {
            return num.toString(16);
        }
    </script>

    </head>
    <body>

        <script type="text/javascript">
            document.write(hex2Decimal("A") + "<br />");
            document.write(decimal2Hex(16) + "<br />");
        </script>
    </body>
</html>
Michel Kogan
Yeah, something like that.Basically the idea is to take a C struct like:<code> struct message_1 { double value_1; unsigned long value_2; signed short value_3; char[6] string_1; }</code>and convert it to a HEX ASCII string and send it to the browser where I convert it back to the individual values (knowing the structure based on a message type) and display some/all of the data for the user.Thanks,Paul
Paul
A: 

Thanks Brian. Really appreciate it.

I was not a registered user when I submitted this question, and had to close my browser for something, and when I went back, I couldn't add a comment anymore, so I created an openId, and logged in with that, but still don't see how to add a comment (wanted to thank you for the code snippet). Is only the original submitter allowed to add comments?

Anyway, thanks again. Been writing C and ASY for years for embedded systems, and am now trying to learn javascript and OOP, etc., and am choking on it , so I appreciate your help.

Paul
You can only make comments on other people's questions once you've gotten 50 rep. There's a contact address at the bottom of the page that you can email to ask the admins to merge the two accounts, so you can be considered owner of this question again, or you can ask on on http://meta.stackoverflow.com/ (but I think that email is preferred).
Brian Campbell
Paul