Print the filled binary word in Racket

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

Example

 (printf "~b" 42) => 101010 Want: 00000000000000000000000000101010 
+4
source share
3 answers

Here is a quick way to do this with Racket 5.3.1 and later:

 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 versions of Racket, you can do this:

 Welcome to Racket v5.3. -> (require srfi/13) -> (string-pad (number->string 42 2) 32 #\0) "00000000000000000000000000101010" 
+8
source

Well, I made it decide together:

 (define (print-word x) (if (not (<= -2147483648 x 4294967295)) (error 'print-word "ERROR This number is bigger than a word ~a" x) (let* ([positive-x (if (< x 0) (+ #x100000000 x) x)] [str (number->string positive-x 2)] [padded-str (string-append (make-string (- 32 (string-length str)) #\0) str)]) (build-string 39 (λ(i) (cond [(= (remainder (+ 1 i) 5) 0) #\space] [else (string-ref padded-str (- i (quotient i 5)))])))))) 

This actually returns a line with spaces between every four digits, as it was actually quite difficult to read differently.

0
source

Well here is a simple, inefficient way to do this:

 (define (pad-left length padding the-str) (if (> length (string-length the-str)) (pad-left length padding (string-append padding the-str)) the-str)) (write (pad-left 32 "0" (format "~b" 42))) 
0
source

All Articles