I'm sure you will find this helpful: http://jsdo.it/tsmallfield/uint8array.
Click on javascript tab.
There will appear the code to convert the Uint8Array in a string. The author shows 2 method:
- The first is about creating a view.
- The second offsetting bytes.
EDIT: report the code for completeness
var buffer = new ArrayBuffer( res.length ), // res is this.response in your case
view = new Uint8Array( buffer ),
len = view.length,
fromCharCode = String.fromCharCode,
i, s, str;
/**
* 1) 8bitใฎ้
ๅใซๅ
ฅใใฆไธไฝใใใใใใ
*/
str = "";
for ( i = len; i--; ) {
view[i] = res[i].charCodeAt(0);
}
for ( i = 0; i < len; ++i ) {
str += fromCharCode( view[i] );
}
/**
* 2) & 0xff ใงไธไฝใใใใใใ
*/
str = "";
for ( i = 0; i < len; ++i ) {
str += fromCharCode( res[i].charCodeAt(0) & 0xff );
}
Answer from user278064 on Stack OverflowI'm sure you will find this helpful: http://jsdo.it/tsmallfield/uint8array.
Click on javascript tab.
There will appear the code to convert the Uint8Array in a string. The author shows 2 method:
- The first is about creating a view.
- The second offsetting bytes.
EDIT: report the code for completeness
var buffer = new ArrayBuffer( res.length ), // res is this.response in your case
view = new Uint8Array( buffer ),
len = view.length,
fromCharCode = String.fromCharCode,
i, s, str;
/**
* 1) 8bitใฎ้
ๅใซๅ
ฅใใฆไธไฝใใใใใใ
*/
str = "";
for ( i = len; i--; ) {
view[i] = res[i].charCodeAt(0);
}
for ( i = 0; i < len; ++i ) {
str += fromCharCode( view[i] );
}
/**
* 2) & 0xff ใงไธไฝใใใใใใ
*/
str = "";
for ( i = 0; i < len; ++i ) {
str += fromCharCode( res[i].charCodeAt(0) & 0xff );
}
function load_binary_resource(url) {
var byteArray = [];
var req = new XMLHttpRequest();
req.open('GET', url, false);
req.overrideMimeType('text\/plain; charset=x-user-defined');
req.send(null);
if (req.status != 200) return byteArray;
for (var i = 0; i < req.responseText.length; ++i) {
byteArray.push(req.responseText.charCodeAt(i) & 0xff)
}
return byteArray;
}
See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data for more details
casting - Converting byte array to string in javascript - Stack Overflow
java - Parse binary string as byte in JavaScript - Stack Overflow
Converting non-unicode binary strings to byte array in Javascript - Stack Overflow
c# - How to convert binary string to bytes[] array? - Stack Overflow
Update 2018 - The easiest way in 2018 should be TextEncoder
let utf8Encode = new TextEncoder();
utf8Encode.encode("abc");
// Uint8Array [ 97, 98, 99 ]
Caveats - The returned element is a Uint8Array, and not all browsers support it.
If you are looking for a solution that works in node.js, you can use this:
var myBuffer = [];
var str = 'Stack Overflow';
var buffer = new Buffer(str, 'utf16le');
for (var i = 0; i < buffer.length; i++) {
myBuffer.push(buffer[i]);
}
console.log(myBuffer);
You need to parse each octet back to number, and use that value to get a character, something like this:
function bin2String(array) {
var result = "";
for (var i = 0; i < array.length; i++) {
result += String.fromCharCode(parseInt(array[i], 2));
}
return result;
}
bin2String(["01100110", "01101111", "01101111"]); // "foo"
// Using your string2Bin function to test:
bin2String(string2Bin("hello world")) === "hello world";
Edit: Yes, your current string2Bin can be written more shortly:
function string2Bin(str) {
var result = [];
for (var i = 0; i < str.length; i++) {
result.push(str.charCodeAt(i).toString(2));
}
return result;
}
But by looking at the documentation you linked, I think that the setBytesParameter method expects that the blob array contains the decimal numbers, not a bit string, so you could write something like this:
function string2Bin(str) {
var result = [];
for (var i = 0; i < str.length; i++) {
result.push(str.charCodeAt(i));
}
return result;
}
function bin2String(array) {
return String.fromCharCode.apply(String, array);
}
string2Bin('foo'); // [102, 111, 111]
bin2String(string2Bin('foo')) === 'foo'; // true
ES6 update
Now, string 'foo' also equals
String.fromCharCode(...[102, 111, 111])
Original answer
Simply apply your byte array to String.fromCharCode. For example
String.fromCharCode.apply(null, [102, 111, 111])
equals 'foo'.
MDN docs here.
Caveat: works for arrays shorter than 65535 - MDN docs here.
Update: I'm not so sure [default] Ajax is the right tool for the job in this case. Regardless of file size, it is generally a good practice to use streams instead to accommodate future scalability, as your current method loads everything at once.
This article goes over how to create a custom ajax transport that wraps an XmlHttpRequest to load the data into an array buffer rather. You could do this, sequentially push the bytes into your main array, and go from there.
Old:
I'm not sure if I properly understood your data representation, but I believe you can just use parseInt() to turn a hex string into decimal:
var data = ['0x00', '0x08', '0x17', '0xA1', '0x01'];
var parsed = [];
for(var i = 0; i < data.length; i++) {
parsed.push(parseInt(data[i], 16));
}
console.log(parsed);
console.log(parseInt('0xA1', 16))
Run code snippetEdit code snippet Hide Results Copy to answer Expand
If this is not what you mean, please comment and I will try to update my answer with a more specific implementation.
Following the suggestion from Haus 's answer I found some more solutions to the problem so I will share my findings here.
My preferred solution is to use ArrayBuffer to access raw data. Unfortunately Ajax does not seem to support it as per this article, although there is an option to add support (which I could not get to work), and there is no straightforward way to create an ArrayBuffer out of string. However XMLHttpRequest supports ArrayBuffer as responseType as explained here so I changed my code to the following, which does what I want:
var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.responseType = 'arraybuffer'; xhr.onload = function() { if (this.status == 200) { var byteTab=[] var uint8View = new Uint8Array(this.response) for (var n = 0; n < uint8View.byteLength; n++) { byteTab.push(uint8View[n]) } } }; xhr.send();Another solution is to get to ArrayBuffer via using Blob, which is explained with an example in this answer
Another option is to use Blob in conjunction with FileReader.readAsBinaryString() along the lines of the example here. Using readAsBinaryString() converts the blob to a unicode string which can then be parsed using charCodeAt()
Parse it to an integer in base 2, then convert to a byte array. In fact, since you've got 16 bits it's time to break out the rarely used short.
short a = Short.parseShort(b, 2);
ByteBuffer bytes = ByteBuffer.allocate(2).putShort(a);
byte[] array = bytes.array();
Another simple approach is:
String b = "0110100001101001";
byte[] bval = new BigInteger(b, 2).toByteArray();