| 47 | } |
| 48 | |
| 49 | function decodeNumeric(stream: BitStream, size: number) { |
| 50 | const bytes: number[] = []; |
| 51 | let text = ""; |
| 52 | |
| 53 | const characterCountSize = [10, 12, 14][size]; |
| 54 | let length = stream.readBits(characterCountSize); |
| 55 | // Read digits in groups of 3 |
| 56 | while (length >= 3) { |
| 57 | const num = stream.readBits(10); |
| 58 | if (num >= 1000) { |
| 59 | throw new Error("Invalid numeric value above 999"); |
| 60 | } |
| 61 | |
| 62 | const a = Math.floor(num / 100); |
| 63 | const b = Math.floor(num / 10) % 10; |
| 64 | const c = num % 10; |
| 65 | |
| 66 | bytes.push(48 + a, 48 + b, 48 + c); |
| 67 | text += a.toString() + b.toString() + c.toString(); |
| 68 | length -= 3; |
| 69 | } |
| 70 | |
| 71 | // If the number of digits aren't a multiple of 3, the remaining digits are special cased. |
| 72 | if (length === 2) { |
| 73 | const num = stream.readBits(7); |
| 74 | if (num >= 100) { |
| 75 | throw new Error("Invalid numeric value above 99"); |
| 76 | } |
| 77 | |
| 78 | const a = Math.floor(num / 10); |
| 79 | const b = num % 10; |
| 80 | |
| 81 | bytes.push(48 + a, 48 + b); |
| 82 | text += a.toString() + b.toString(); |
| 83 | } else if (length === 1) { |
| 84 | const num = stream.readBits(4); |
| 85 | if (num >= 10) { |
| 86 | throw new Error("Invalid numeric value above 9"); |
| 87 | } |
| 88 | |
| 89 | bytes.push(48 + num); |
| 90 | text += num.toString(); |
| 91 | } |
| 92 | |
| 93 | return { bytes, text }; |
| 94 | } |
| 95 | |
| 96 | const AlphanumericCharacterCodes = [ |
| 97 | "0", "1", "2", "3", "4", "5", "6", "7", "8", |