Skip to content

Instantly share code, notes, and snippets.

@christroutner
Last active September 8, 2020 16:58
Show Gist options
  • Save christroutner/dc5ca1668c10f2b808570343fc1a9877 to your computer and use it in GitHub Desktop.
Save christroutner/dc5ca1668c10f2b808570343fc1a9877 to your computer and use it in GitHub Desktop.
Working with Buffers and Hex Strings

Working with JavaScript Buffers, Hex, and Strings

// Start with a normal base-10 number.
const numNum = 123; // 7B in hex
console.log(`numNum: `, numNum);
// numNum:  123

// Convert the Number to a String
const numStr = numNum.toString();
console.log(`numStr: ${numStr}`);
// numStr: 123

// Convert the number to a hexadecimal string.
const numHex = numNum.toString(16);
console.log(`numHex: ${numHex}`);
// numHex: 7b

// Convert the hexadecimal string into a Buffer
const numBuf = Buffer.from(numHex, "hex");
console.log(`numBuf: `, numBuf);
// numBuf:  <Buffer 7b>

// Convert the Buffer back to a hexadecimal string
const numStr2 = numBuf.toString("hex");
console.log(`numStr2: `, numStr2);
// numStr2:  7b

// Convert the hexadecimal string into a base-10 Number
const numNum2 = parseInt(numStr2, 16);
console.log(`numNum2: `, numNum2);
// numNum2:  123
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment