[英]changing a specific index bit in a binary number in Scheme(Racket)
I need to implement in Scheme the possibility to change a specific bit in a binary number. 我需要在Scheme中实现更改二进制数中特定位的可能性。
the input are : 1.binary number , 2.index of the bit to change, 3.value to set in that index. 输入为:1.二进制数,2.要更改的位的索引,3.在该索引中设置的值。
How can that be implemented? 如何实现?
Here is the beginning of a solution. 这是解决方案的开始。 Can you see what's need to be done in the remaining case?
您能看到剩下的情况下需要做什么吗?
; bit-index->number : natural -> natural
; return the number which in binary notation has a 1 in position n
; and has zeros elsewhere
(define (bit-index->number n)
(expt 2 n))
; Example
(displayln (number->string (bit-index->number 3) 2))
; 1000
; is-bit-set? : index natural -> boolean
; is bit n set in the number x?
(define (is-bit-set? n x)
; the bitwise-and is zero unless bit n is set in the number x
(not (zero? (bitwise-and (bit-index->number n) x))))
(define (set-bit! n x b)
(cond
[(= b 1) ; we need to set bit n in x to 1
(cond
[(is-bit-set? n x) x] ; it was already set
[else (+ x (bit-index->number n))])] ; add 2^n
[(= b 0)
; <what goes here?>
]))
(define (set-bit value index n)
(let ([mask (arithmetic-shift 1 index)])
(cond [(= value 0) (bitwise-and (bitwise-not mask) n)]
[(= value 1) (bitwise-ior mask n)])))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.