Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
hex16.js
// 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
You can’t perform that action at this time.