Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Last active November 16, 2022 22:08
Show Gist options
  • Save DmitrySoshnikov/798ddbbd67f14f1db6230dbde8175299 to your computer and use it in GitHub Desktop.
Save DmitrySoshnikov/798ddbbd67f14f1db6230dbde8175299 to your computer and use it in GitHub Desktop.
/**
* int16, and uint16 numbers in JS.
*
* by Dmitry Soshnikov <[email protected]>
*/
const assert = require('assert');
/**
* Converts a number to signed 16-bit integer.
*/
function int16(v) {
return (v << 16) >> 16;
}
/**
* Converts a number to unsigned 16-bit integer.
*/
function uint16(v) {
return v & 0xFFFF;
}
// ------------------------------------------
// Tests
// int32
assert.equal(0xFFFF, 65535);
assert.equal(~0x0, -1);
// int16
assert.equal(int16(0xFFFF), -1);
assert.equal(int16(~0x0), -1);
// uint16
assert.equal(uint16(0xFFFF), 65535);
assert.equal(uint16(~0x0), 65535);
console.log('All tests passed!');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment