Skip to content

Instantly share code, notes, and snippets.

@fnky
Last active June 30, 2016 07:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fnky/b4a3edb6a6aad87f6560e99f2c183d87 to your computer and use it in GitHub Desktop.
Save fnky/b4a3edb6a6aad87f6560e99f2c183d87 to your computer and use it in GitHub Desktop.
Buffer being wrong?
'use strict'
const chr = (codePoint) => String.fromCharCode(codePoint)
function bin2hex (s) {
let o = ''
for (let i = 0, l = s.length; i < l; i++) {
let n = s.charCodeAt(i).toString(16)
o += (n.length < 2 ? '0' + n : n)
}
return o
}
function constructPacket (address, port, opcode) {
const cip = address.split('.')
const cport = port
let packet = 'VCMP'
packet += chr(cip[0])
packet += chr(cip[1])
packet += chr(cip[2])
packet += chr(cip[3])
packet += chr(cport & 0xFF)
packet += chr(cport >> 8 & 0xFF)
packet += opcode
return packet
}
const packet = constructPacket('192.168.200.103', 5192, 'i')
console.log('binary =>', packet)
console.log('bin2hex =>', bin2hex(packet))
console.log('Buffer =>', Buffer.from(packet))
console.log('Buffer.toString =>', Buffer.from(packet).toString())
// binary => VCMPÀ¨ÈgHi
// bin2hex => 56434d50c0a8c867481469
// Buffer => <Buffer 56 43 4d 50 c3 80 c2 a8 c3 88 67 48 14 69>
// Buffer.toString => VCMPÀ¨ÈgHi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment