您的位置:首页 > 其它

newlisp转换10进制正整数到二进制串

2016-07-26 20:14 351 查看

二进制字符串转换成整数

(int "0b100100100101001001000000000000000000000010100100")
;-> 160881958715556

十进制正整数转换成二进制list

本来想直接转成string,后来想list更通用,所以就先转成list
;; @arg in-value decimal value
;; @return binary value list
;; @example (get-binary-str 8) => (1 0 0 0)
(define (get-binary-value int-value)
(if (< int-value 0)
(throw "cannot handle negative integer")
)
(setq r '())
(setq v int-value)
(setq divided-result nil) ;; 商
(setq divided-left nil) ;; 余数
(do-until (= 0 divided-result)
(setq divided-result (/ v 2))
(setq divided-left (% v 2))
(push divided-left r)
(setq v divided-result)
)
r
)

调用示例:
负数不处理
> (catch (get-binary-value -8))
"cannot handle negative integer"

正整数处理 (catch (get-binary-value 8))
(1 0 0 0)

十进制正整数转换成二进制string

(define (get-binary-str int-value)
(setq r (get-binary-value int-value))
(setq r2 (map (fn (e) (string e)) r))
(join r2 "")
)

现在来调用下
> (catch (get-binary-str 8))
"1000"
> (catch (get-binary-str 2))
"10"

进一步,增加宽度设置参数

;; @arg in-value decimal value
;; @width list size, fill in 0 in front of list if not enough
;; @return binary value list
;; @example (get-binary-str 8) => (1 0 0 0)
(define (get-binary-value int-value width)
(if (< int-value 0)
(throw "cannot handle negative integer")
)
(setq r '())
(setq v int-value)
(setq divided-result nil) ;; 商
(setq divided-left nil) ;; 余数
(do-until (= 0 divided-result)
(setq divided-result (/ v 2))
(setq divided-left (% v 2))
(push divided-left r)
(setq v divided-result)
)
(setq left (- width (length r)))
(dotimes (n left)
(push 0 r)
)
r
)

(define (get-binary-str int-value width)
(setq r (get-binary-value int-value width))
(setq r2 (map (fn (e) (string e)) r))
(join r2 "")
)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  newlisp