четверг, 7 января 2021 г.

Emacs Lisp. Представление чисел в различных системах счисления (dec, hex, bin)

При работе с текстом мне постоянно приходится менять представление чисел, переводя из одной системы счисления в другую. Что я хотел сказать? Emacs прекрасен. Взял и накидал несколько функций на elisp. Теперь, выделив число в тексте, можно быстро представить его в другой системе. Ниже привожу листинг.

;; convert decimal to binary
(defun pa23-dec2bin (start end)
  "Convert decimal to binary."
  (interactive "r")
  (let ((var 0) (res ""))
    (setq var (string-to-number (buffer-substring-no-properties start end)))
    (while (not (= var 0))
      (setq res (concat (if (= 1 (logand var 1)) "1" "0") res))
      (setq var (lsh var -1)) )
    (if (string= res "") (setq res "0"))
    (delete-region start end)
    (insert res) ) )

;; convert decimal to hexadecimal
(defun pa23-dec2hex (start end)
  "Convert decimal to hexadecimal."
  (interactive "r")
  (let ((var 0) (res ""))
    (setq var (string-to-number (buffer-substring-no-properties start end)))
    (setq res (upcase (format "%x" var)))
    (delete-region start end)
    (insert res) ) )

;; convert hexadecimal to binary
(defun pa23-hex2bin (start end)
  "Convert hexadecimal to binary."
  (interactive "r")
  (let ((var "") (res ""))
    (setq var (string-to-number (buffer-substring-no-properties start end) 16))
    (while (not (= var 0))
      (setq res (concat (if (= 1 (logand var 1)) "1" "0") res))
      (setq var (lsh var -1)) )
    (if (string= res "") (setq res "0"))
    (delete-region start end)
    (insert res) ) )

;; convert hexadecimal to decimal
(defun pa23-hex2dec (start end)
  "Convert hexadecimal to decimal."
  (interactive "r")
  (let ((var 0) (res ""))
    (setq var (string-to-number (buffer-substring-no-properties start end) 16))
    (setq res (number-to-string var))
    (delete-region start end)
    (insert res) ) )

;; convert binary to decimal
(defun pa23-bin2dec (start end)
  "Convert binary to decimal."
  (interactive "r")
  (let ((var 0) (res ""))
    (setq var (string-to-number (buffer-substring-no-properties start end) 2))
    (setq res (number-to-string var))
    (delete-region start end)
    (insert res) ) )

;; convert binary to hexadecimal
(defun pa23-bin2hex (start end)
  "Convert binary to hexadecimal."
  (interactive "r")
  (let ((var 0) (res ""))
    (setq var (string-to-number (buffer-substring-no-properties start end) 2))
    (setq res (upcase (format "%x" var)))
    (delete-region start end)
    (insert res) ) )

Комментариев нет:

Отправить комментарий