I have a question concerning Racket. Given 2 string binary numbers, I would like to obtain their sum in a string binary number. The function should take into account carry bits and a possible overflow. So the function should look like this:
(define (binary-sum a b) ...)
For example:
(binary-sum "010" "001")
"011"
Or:
(binary-sum "0010" "1011")
"1101"
Or in case of overflow:
(binary-sum "1111" "0001")
"overflow"
Please identify any packages I need.
Thank you!
Binary values in Racket are specified using the prefix #b
. Using that, we can create the following function:
> (define (binary-sum a b)
(+ (string->number (string-append "#b" a))
(string->number (string-append "#b" b))))
> (binary-sum "010" "001")
3
To format the output as binary as well, we can use ~r
, like so:
> (define (binary-sum a b)
(~r (+ (string->number (string-append "#b" a))
(string->number (string-append "#b" b))) #:base 2))
> (binary-sum "010" "001")
011
And finally, to add your overflow feature, we can simply compare the length of our result as a string to the length of one of the parameters.
(define (binary-sum a b)
(let ((sum (~r (+ (string->number (string-append "#b" a))
(string->number (string-append "#b" b)))
#:base 2)))
(if (> (string-length sum)
(string-length a))
"overflow"
sum)))
Which behaves exactly as your question specifies. Let me know if you have any remaining doubts or confusion. Good luck!
Edit: Just wanted to note that if you ever need to merely add two binary values and don't mind getting an integer back, you can always just do it like so:
> (+ #b010 #b001)
3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.