Skip to content

Instantly share code, notes, and snippets.

@enjalot
Created May 2, 2013 22:48
Show Gist options
  • Save enjalot/5506058 to your computer and use it in GitHub Desktop.
Save enjalot/5506058 to your computer and use it in GitHub Desktop.
understanding bits of numbers
{"description":"understanding bits of numbers","endpoint":"","display":"svg","public":true,"require":[],"fileconfigs":{"inlet.js":{"default":true,"vim":false,"emacs":false,"fontSize":12},"_.md":{"default":true,"vim":false,"emacs":false,"fontSize":12},"config.json":{"default":true,"vim":false,"emacs":false,"fontSize":12}},"fullscreen":false,"play":false,"loop":false,"restart":false,"autoinit":true,"pause":true,"loop_type":"period","bv":false,"nclones":15,"clone_opacity":0.4,"duration":3000,"ease":"linear","dt":0.01,"thumbnail":"http://i.imgur.com/pNLrnaS.png"}
//UUID
/*
A UUID is a 16-octet (128-bit) number. In its canonical form, a UUID is represented by
32 hexadecimal digits, displayed in five groups separated by hyphens, in the form
8-4-4-4-12 for a total of 36 characters (32 alphanumeric characters and four hyphens).
For example:
550e8400-e29b-41d4-a716-446655440000
The number of possible UUIDS is 340,282,366,920,938,463,463,374,607,431,768,211,456
(16^32 or 2^128), or about 3.4 × 10^38.
*/
var svg = d3.select("svg");
var ng = svg.append("g")
.attr("transform", "translate(100,100)")
numberForms(ng, 300)
function numberForms(group,n) {
//@params
// group: d3 selection to update our text
//display a number "n" in integer, hex, binary
//assumes positive integers
g = group.selectAll("g.num").data([0])
genter = g.enter()
.append("g").classed("num", true)
genter.append("text").classed("int", true)
genter.append("text").classed("hex", true)
.attr("y", "1em")
genter.append("text").classed("bin", true)
.attr("y", "2em")
var hex = n.toString(16);
hex = zeropad(hex.length, 2) + hex
var binary = n.toString(2);
zeropadding = zeropad(binary.length, 8)
binary = zeropadding + binary
binary = splitNumber(binary, 8)
g.select("text.int")
.text("decimal: " + n)
g.select("text.hex")
.text("hex: " + hex)
g.select("text.bin")
.text("binary:")
.selectAll("tspan.chunks")
.data(binary).enter().append("tspan")
.text(function(d){ return " " + d })
}
function numberVis(g,n) {
//visualize a number in terms of bits and bytes
}
function zeropad(l, p) {
//given a number of l digits, give a string of 0s to pad with
//so that there is always a multiple of p digits
n = l % p;
if(n)
return d3.range(p - n).map(function() { return "0" }).join("")
return "";
}
function splitNumber(s, l) {
//given a number (represented as a string "s")
//split it into chunks of size l
var chunks = [];
var chunk = "";
for(var i = s.length; i--;) {
chunk = s[i] + chunk;
if(i % l === 0) {
chunks.push(chunk);
chunk = "";
}
}
return chunks
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment