Last active
February 13, 2024 07:49
-
-
Save taniarascia/d1a99316f86d3726a1a768a08dbc4fea to your computer and use it in GitHub Desktop.
hex16.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// echo -en "\x01\x02\x03\x04\x05\x06hello world\x07\x08\x09\x10goodbye world\x11\x12\x13\x14\x15" > data | |
let fs = require('fs') | |
let file = process.argv.slice(2)[0] | |
function hexdump(file) { | |
let buffer = fs.readFileSync(file) | |
let lines = [] | |
for (let i = 0; i < buffer.length; i += 16) { | |
let address = i.toString(16).padStart(8, '0') | |
let block = buffer.slice(i, i + 16) | |
let array16 = [] | |
for (let j = 0; j < block.length; j += 2) { | |
if (j < block.length - 1) { | |
array16.push((block[j] << 8) | (block[j + 1] << 0)) | |
} | |
} | |
let hexString = array16.map(value => value.toString(16).padStart(4, '0')).join(' ') | |
lines.push(`${address} ${hexString}`) | |
} | |
return lines.join('\n') | |
} | |
console.log(hexdump(file)) | |
// 00000000 0102 0304 0506 6865 6c6c 6f20 776f 726c | |
// 00000010 6407 0809 1067 6f6f 6462 7965 2077 6f72 | |
// 00000020 6c64 1112 1314 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment