Search code examples
binaryhexschemeracketoctal

How to do floating conversions in scheme (drracket)?


I want to do some conversions of bin to hex , hex to bin, hex to dec etc in scheme language. but I'm not used to drracket like an advanced user. I need to implement 3x4 as all possible pairs of binary, hexadecimal, octal and decimal.

So far I only accomplished to implement bin to dec but I didn't handle the idea of the others, can anyone give me some tips, idea or code blocks and all kind of helps to improve my implementation?

I placed my bin to dec below, thank you all in advance.

(define (bin-to-dec x)
  (if (zero? x)
      x
      (+ (modulo x 10) (* 2 (bin->dec (quotient x 10))))))

Have a nice day, keep safe.


Solution

  • The second you have a fixnum (integer) in Scheme the base is not important as the number does not have a base. The reason is that base is related to visual encoding of a number. Eg. 10 can be written as #b1010 #xa #o12 and all of these will in a Scheme repl display 10 since the repl shows the number representations in decimal:

    #b1010 ; ==> 10
    #xa    ; ==> 10
    #o12   ; ==> 10
    

    If you want to print a number in a different base you do that when the number goes from a number to a visualized representation (eg. string). Scheme has this with number->string

    (number->string 10 2)  ; ==> "1010"
    (number->string 10 16) ; ==> "a"
    (number->string 10 8)  ; ==> "12"
    

    There is also string->int that does the reverse:

    (string->number "1010" 2) ; ==> 10
    (string->number "a" 16)   ; ==> 10
    (string->number "12" 8)   ; ==> 10
    

    Your implementation bin->dec takes a number of any base as input and transforms its decimal visualization as if it was binary to decimal. eg

    (bin-to-dec #b1010) ; ==> 2