Skip to content

Instantly share code, notes, and snippets.

@dotproto
Last active Dec 30, 2015
Embed
What would you like to do?
Utilities for working with binary values in JavaScript.
// Numbers greater than (Math.pow(2,32) - 1) are subject to unexpected results
// bit-level operations. For example,
//
// (Math.pow(2,32) >> 1 === 0) // True
// (Math.pow(2,32) + 1 >> 1 === 0) // True
// (Math.pow(2,32) + 2 >> 1 === 1) // True
//
// As such, all methods defined here will throw an error on values above this safe limit.
var INT_MAX = Math.pow(2, 32) - 1;
var BYTE_MAX = 8;
// ---
function bitString(value) {
var castValue = value.toString(2)
if (castValue.length > BYTE_MAX) {
throw new Error("The value provided (" + value + ") cannot fit inside a single byte.")
}
return ('00000000' + castValue.toString()).substr(castValue.toString().length)
}
function hexString(value) {
var castValue = null;
switch (typeof value) {
case "number":
return value.toString(16);
break;
case "string":
return byteAsHex(value.charCodeAt(0));
break;
default:
throw new Error("The value provided (" + value+ ") is type '" + (typeof value) + "' and cannot be converted to hex");
}
}
// NOTE: ES 5.1 defines the basic size of a character as 16-bits. For the purpose of this file
// a word will be defined as a 16-bit value.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment