Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a padded binary word in Racket

Tags:

racket

I want to print a padded to 32 bits word in binary in Racket. I know about printf and "~b", but I want it padded to be 32 bits long each time. How do I do this?

Example

(printf "~b" 42) 
=> 101010
Want: 00000000000000000000000000101010
like image 759
Theo Belaire Avatar asked Jan 30 '13 03:01

Theo Belaire


1 Answers

Here's a concise way to do it with Racket 5.3.1 and above:

Welcome to Racket v5.3.2.3.
-> (require racket/format)
-> (~r 42 #:base 2 #:min-width 32 #:pad-string "0")
"00000000000000000000000000101010"

See racket/format for more details.

In older Racket versions, you can do this:

Welcome to Racket v5.3.
-> (require srfi/13)
-> (string-pad (number->string 42 2) 32 #\0)
"00000000000000000000000000101010"
like image 182
Asumu Takikawa Avatar answered Nov 18 '22 01:11

Asumu Takikawa