I'm working on this real head scratcher!
I'm successfully adding byte values to a Uint8ClampedArray and using the array to generate a byte string using this function:
this.utf8ArrayToStr = function(array) {
var s = '';
for (var i = 0; i < array.length; i++) {
s += String.fromCharCode(array[i]);
}
return s;
};
This works a treat and successfully generates the correct byte sequence.
The problem is that not all browsers support Uint8ClampedArray and I specifically need it to work on Android browsers.
I tried using a standard Uint8Array but it results in extra byte values in the resulting string, causing erroneous behaviour.
I also found a small shim here, but it did not work, again producing extra output: https://gist.github.com/gengkev/2295355
Is there anyway I could make Uint8Array act as Uint8ClampedArray, or more specifically, clamp the values while generating the string in the function above?
UPDATE: It looks like I'm getting somewhere using an standard array but there's still some messed up characters causing problems.
I think you shouldn't be using Uint8Array to store your data - it simply doesn't work like a Uint8ClampedArray. For example:
a = new Uint8Array(1);
b = new Uint8ClampedArray(1);
a[0] = 256;
b[0] = 256;
a[0] === 0; // true
b[0] === 255; // true
I would just use a regular array (if that's an option) and clamp the values when you store them into it, or when you read them to generate your string like this:
s += String.fromCharCode(Math.max(0, Math.min(255, array[i])));