hex.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. function byteLength (string) {
  2. return string.length >>> 1
  3. }
  4. function toString (buffer) {
  5. const len = buffer.byteLength
  6. buffer = new DataView(buffer.buffer, buffer.byteOffset, len)
  7. let result = ''
  8. let i = 0
  9. for (let n = len - (len % 4); i < n; i += 4) {
  10. result += buffer.getUint32(i).toString(16).padStart(8, '0')
  11. }
  12. for (; i < len; i++) {
  13. result += buffer.getUint8(i).toString(16).padStart(2, '0')
  14. }
  15. return result
  16. }
  17. function write (buffer, string, offset = 0, length = byteLength(string)) {
  18. const len = Math.min(length, buffer.byteLength - offset)
  19. for (let i = 0; i < len; i++) {
  20. const a = hexValue(string.charCodeAt(i * 2))
  21. const b = hexValue(string.charCodeAt(i * 2 + 1))
  22. if (a === undefined || b === undefined) {
  23. return buffer.subarray(0, i)
  24. }
  25. buffer[offset + i] = (a << 4) | b
  26. }
  27. return len
  28. }
  29. module.exports = {
  30. byteLength,
  31. toString,
  32. write
  33. }
  34. function hexValue (char) {
  35. if (char >= 0x30 && char <= 0x39) return char - 0x30
  36. if (char >= 0x41 && char <= 0x46) return char - 0x41 + 10
  37. if (char >= 0x61 && char <= 0x66) return char - 0x61 + 10
  38. }