Skip to content Skip to sidebar Skip to footer

Retrieving Binary Data In Javascript (Ajax)

Im trying to get this remote binary file to read the bytes, which (of course) are supossed to come in the range 0..255. Since the response is given as a string, I need to use charC

Solution 1:

The following code has been extracted from an answer to this StackOverflow question and should help you work around your issue.

function stringToBytesFaster ( str ) { 
    var ch, st, re = [], j=0;
    for (var i = 0; i < str.length; i++ ) { 
        ch = str.charCodeAt(i);
        if(ch < 127)
        {
            re[j++] = ch & 0xFF;
        }
        else
        {
            st = [];    // clear stack
            do {
                st.push( ch & 0xFF );  // push byte to stack
                ch = ch >> 8;          // shift value down by 1 byte
            }
            while ( ch );
            // add stack contents to result
            // done because chars have "wrong" endianness
            st = st.reverse();
            for(var k=0;k<st.length; ++k)
                re[j++] = st[k];
        }
    }   
    // return an array of bytes
    return re; 
}

var str = "\x8b\x00\x01\x41A\u1242B\u4123C";

alert(stringToBytesFaster(str)); // 139,0,1,65,65,18,66,66,65,35,67

Solution 2:


Post a Comment for "Retrieving Binary Data In Javascript (Ajax)"