Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Last active Jun 10, 2021
Embed
What would you like to do?
/**
* int16, and uint16 numbers in JS.
*
* by Dmitry Soshnikov <dmitry.soshnikov@gmail.com>
*/
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