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获取git标签名并自动更改版本
- newlisp string转换成数值
- newlisp中的if语句
- newlisp中string转换成list
- newlisp安装
- 为Emacs 24.3配置newLISP开发环境
- newlisp 使用crypto模块
- 修改配置文件
- newlisp set 函数
- Say bye to CMake and Makefile
- 遍历目录树,清理编译目录
- newlisp 获取cpu信息
- 用newLisp开发网站六 REST API返回JSON串
- 禁止笔记本的touchpad
- newLISP中的字典类型
- 改进的newLISP编译C++的脚本
- CentOS 5.9+ 编译newlisp
- 远程运行newLISP代码
- 用newLISP通过SMTP服务器发送邮件
- 用newLISP读取Hive的元数据