1

I have to validate whether a provided parameter is a type of byte array or not using Javascript. How can I achieve this? Please advice.

AnOldSoul
  • 4,017
  • 12
  • 57
  • 118
  • can you post an example of a valid array, and how its going to be created? – webdeb Aug 10 '16 at 00:17
  • http://stackoverflow.com/questions/12332002/how-to-store-a-byte-array-in-javascript, here is how to create a byte array on javascript then you just need to compare the parameter with the selected type array like ```param instanceof UInt8Array``` – Miguel Lattuada Aug 10 '16 at 00:21
  • @MiguelLattuada it does not always has to be an instance of **UInt8Array**, it could be also an **Int8Array** for example or **Uint8ClampedArray**, I would suggest to check for the existence of the `byteLength` – webdeb Aug 10 '16 at 00:25

1 Answers1

2

Because its not clear which type / instance of a Typed-Array you are trying to check, here an universal check. check if byteLength is present, then it should be a byteArray

function isByteArray(array) {
  if (array && array.byteLength !== undefined) return true;
  return false;
}

Modified version of Jonis Answer: (this will return an ArrayBuffer, which is designed to contain bytes)

function toUTF8Array(str) { var utf8 = new ArrayBuffer(str.length);

for (var i=0; i < str.length; i++) {
    var charcode = str.charCodeAt(i);
    if (charcode < 0x80) {
      utf8[i] = charcode;
      continue;
    }

    if (charcode < 0x800) {
        utf8[i] = (0xc0 | (charcode >> 6), 
                  0x80 | (charcode & 0x3f));
      continue;
    }

    if (charcode < 0xd800 || charcode >= 0xe000) {
        utf8[i] = (0xe0 | (charcode >> 12), 
                  0x80 | ((charcode>>6) & 0x3f), 
                  0x80 | (charcode & 0x3f));
        continue;
    }

    i++;
    charcode = 0x10000 + (((charcode & 0x3ff)<<10)
               | (str.charCodeAt(i) & 0x3ff));

    utf8[i - 1] = (0xf0 | (charcode >>18), 
               0x80 | ((charcode>>12) & 0x3f), 
               0x80 | ((charcode>>6) & 0x3f), 
               0x80 | (charcode & 0x3f));


   }

    return utf8;
}
webdeb
  • 12,993
  • 5
  • 28
  • 44
  • I used the answer by Joni in http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array to convert a string to byte array and used your method to validate it. But returns false. Any ideas? :( – AnOldSoul Aug 10 '16 at 00:48
  • well, its not a typed-array what Joni is offering.. try to modify Jonis function to return an ArrayBuffer instead of a simple array.. Of course you could set a custom property to this array to identify it later, but then its still !== TypedArray – webdeb Aug 10 '16 at 00:59
  • @mayooran see the edits, this will return an ArrayBuffer – webdeb Aug 10 '16 at 09:46