16-bit binary grid
J, 26 bytes
(' ';' # '){~4 4$_16{.#:
An anonymous verb. Thankfully, J is very good at drawing boxes. Let's try it out:
f =. (' ';' # '){~4 4$_16{.#:
f 4242
+---+---+---+---+
| | | | # |
+---+---+---+---+
| | | | |
+---+---+---+---+
| # | | | # |
+---+---+---+---+
| | | # | |
+---+---+---+---+
As some commenters have mentioned, the way J draws boxes is system-dependent: on some platforms, this code will work under the default settings, but on others, the boxes will be drawn using Unicode line drawing characters. (The commands 9!:6
and 9!:7
allow you to query and set the characters to draw boxed values with, respectively.)
JavaScript (ES6), 102
... or 96 using return
instead of console.log
.
Test running the snippet below in an EcmaScript 6 compliant browser.
f=n=>{for(o=h=`
+---+---+---+---+
`,z=16;z--;n/=2)o=(z&3?'':h+'|')+` ${' #'[n&1]} |`+o;console.log(o)}
// TEST
console.log=x=>O.innerHTML=x+O.innerHTML
function test(n) { f(n); console.log(n); }
<input id=I value=4680><button onclick='test(+I.value)'>-></button>
<pre id=O></pre>
Befunge-93, 196 218 bytes
&00p12*v>>4>"---+",v v <
v*:*:*:< | :-1,,,< #
>:*2/10p^ >"+",25*,10g|
> #v^# $< @
25*,^ >4" |",,v ,*<>
v>"#",00g10g-00p 10g
|`-1g01g00 <>48^
v>" ",10g
>2/10p>"| ",,1-:#^_$>^
To run the program...
- Go to the online interpreter.
- Paste this code in the big text box.
- Click
Show
. - Input the desired number in the
Input
box. - Click
Run
. (Or changeSlow
to something like 5 milliseconds and then clickShow
.) - Ta-da!
Output for 4242:
+---+---+---+---+
| | | | # |
+---+---+---+---+
| | | | |
+---+---+---+---+
| # | | | # |
+---+---+---+---+
| | | # | |
+---+---+---+---+
Output for 33825:
+---+---+---+---+
| # | | | |
+---+---+---+---+
| | # | | |
+---+---+---+---+
| | | # | |
+---+---+---+---+
| | | | # |
+---+---+---+---+
Explanation
Oh goodness, what have I got myself into? Well, here goes! (Irrelevant code is replaced with .
s.)
Part 1: Get input (store in 0,0) and calculate 32768 (store in 1,0).
&00p12*v>
v*:*:*:<
>:*2/10p^
Part 2: Print out "+---+---+---+---".
>4>"---+",v
| :-1,,,<
Part 3: Print "+" and a newline and check to see if (1,0) is 0 (i.e. we're done). If so, terminate. Otherwise, continue.
........... v <
| ....... #
>"+",25*,10g|
v.# $< @
>4" |",,v ...
Part 4: Get binary digits of input, updating (0,0) and (1,0) as we go along. Print the right things. I take advantage of Befunge's wrap-around behavior.
..... >4" |",,v ,*<.
v>"#",00g10g-00p 10g
|`-1g01g00 <>48^
v>" ",10g
>2/10p>"| ",,1-:#^_...
Part 5: Print a newline and go back to the part that prints "+---+---+---+---+". Wrap-around trick is used.
> #.^. .. .
25*,^ ......... ...>
................ ...
......... .....
........
.................._$>^