簡體   English   中英

在Scheme(Racket)中更改二進制數中的特定索引位

[英]changing a specific index bit in a binary number in Scheme(Racket)

我需要在Scheme中實現更改二進制數中特定位的可能性。

輸入為:1.二進制數,2.要更改的位的索引,3.在該索引中設置的值。

如何實現?

這是解決方案的開始。 您能看到剩下的情況下需要做什么嗎?

; 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM