Skip to content

Instantly share code, notes, and snippets.

@DefinitelyMaybe
Created August 15, 2023 05:40
Show Gist options
  • Save DefinitelyMaybe/a8d494c022b50986e6f0a8f2b96e6e69 to your computer and use it in GitHub Desktop.
Save DefinitelyMaybe/a8d494c022b50986e6f0a8f2b96e6e69 to your computer and use it in GitHub Desktop.
Test2
function uint8ArrayToHex(uint8Array) {
return Array.from(uint8Array)
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
}
function extractFlagAndPID(inputArray) {
const first3Bits = inputArray[0] & 0b111;
const next13Bits = ((inputArray[0] & 0b00011111) << 8) | inputArray[1];
return {
flags: first3Bits.toString(16),
pid: next13Bits.toString(16).padStart(4, "0"),
};
}
function concatUint8Arrays(a: Uint8Array, b: Uint8Array): Uint8Array {
const result = new Uint8Array(a.length + b.length);
result.set(a);
result.set(b, a.length);
return result;
}
try {
const packetSize = 188;
let prevChunk = new Uint8Array();
let index = 0;
const uids = {};
for await (const chunk of Deno.stdin.readable) {
let data = null;
if (prevChunk.length > 0) {
data = concatUint8Arrays(prevChunk, chunk);
}
if (!data) {
data = chunk;
}
for (let i = 0; i < data.length / packetSize; i++) {
const offset = i * 188;
const syncByte = uint8ArrayToHex(data.slice(offset, offset + 1));
if (syncByte != "47") {
throw `Error: No sync byte present in packet ${index}, offset ${
index * 188
}`;
}
index++;
const { flags, pid } = extractFlagAndPID(
data.slice(offset + 1, offset + 3)
);
if (!(pid in uids)) {
uids[pid] = null;
}
}
if (data.length % packetSize != 0) {
prevChunk = data.slice(Math.floor(data.length / packetSize));
}
}
[...Object.keys(uids)].sort().forEach((pid) => {
let x = pid.replace(/0+/, "");
if (x.length == 0) {
x = "0";
}
console.log(`0x${x}`);
});
Deno.exit(0);
} catch (error) {
console.error(error);
Deno.exit(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment