Converting a String object to individual bytes

E

Erinys

Hi,

I need to access the individual bytes in a string in my javascript
function.
If the characters in the string were all ascii characters then there
would not be a problem, however in my case the string may contain
ISO-2022-JP or UTF8 characters, so these characters may be larger than
1 byte each.
Is there a way to extract the individual bytes, or convert a string to
an array of bytes in javascript?

Any suggestions would be great.

Thanks in advance,

Erinys.
 
G

Grant Wagner

Erinys said:
Hi,

I need to access the individual bytes in a string in my javascript
function.
If the characters in the string were all ascii characters then there
would not be a problem, however in my case the string may contain
ISO-2022-JP or UTF8 characters, so these characters may be larger than
1 byte each.
Is there a way to extract the individual bytes, or convert a string to
an array of bytes in javascript?

Any suggestions would be great.

Thanks in advance,

Erinys.

<script type="text/javascript">

// test string
var s = 'your string' +
String.fromCharCode(1024, 1025, 1026, 1027) +
String.fromCharCode(65535);

// generate the byte array
var bytes = [];
for (var ii = 0; ii < s.length; ++ii) {
var c = s.charCodeAt(ii);
// reverse these, depending on how
// you want to store the results
bytes.push(c >>> 8, c & 255);
}

// output the results
for (var ii = 0; ii < bytes.length; ii += 2) {
document.write(
bytes[ii] + ',' +
bytes[ii + 1] + '<br>'
);
}

</script>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top