All files / util hexToAb.ts

100% Statements 11/11
100% Branches 0/0
100% Functions 1/1
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36                                  1x   1x   1x 1x 1x   1x   2x 2x 2x   1x     1x  
/**
 * 16进制字符串转ArrayBuffer
 * @method hexToAb
 * @see https://caniuse.com/#search=ArrayBuffer
 * @param {String} str 需要转换的16进制字符串
 * @return {ArrayBuffer} 被转换后的 ArrayBuffer 对象
 * @example
 * import { hexToAb } from '@spore-ui/tskit';
 * var ab = hexToAb();
 * ab.byteLength; // => 0
 * ab = hexToAb('abcd');
 * var dv = new DataView(ab);
 * ab.byteLength; // => 2
 * dv.getUint8(0); // => 171
 * dv.getUint8(1); // => 205
 */
 
export function hexToAb(str: string): ArrayBuffer {
  if (!str) {
    return new ArrayBuffer(0);
  }
  const buffer = new ArrayBuffer(Math.ceil(str.length / 2));
  const dataView = new DataView(buffer);
  let index = 0;
  let i;
  const len = str.length;
  for (i = 0; i < len; i += 2) {
    const code = parseInt(str.substr(i, 2), 16);
    dataView.setUint8(index, code);
    index += 1;
  }
  return buffer;
}
 
export default hexToAb;