Display the binary version of hex value in status bar

299 views Asked by At

I am doing a lot of embedded C programming right now, which means that I am writing things like this all the time:

(ioe_extra_A & 0xE7)

It would be super useful, if when put my cursor on the 0xE7, emacs would display "0b1110 0111" in the status bar or mini-buffer, so I could check that my mask is what I meant it to be.

Typically, no matter what it is I want emacs to do, 10 minutes of Googling will turn up the answer, but for this one, I have exhausted my searching skills and still not turned up an answer.

Thanks ahead of time.

1

There are 1 answers

1
legoscia On BEST ANSWER

This seems to work:

(defvar my-hex-idle-timer nil)

(defun my-hex-idle-status-on ()
  (interactive)
  (when (timerp my-hex-idle-timer)
    (cancel-timer my-hex-idle-timer))
  (setq my-hex-idle-timer (run-with-idle-timer 1 t 'my-hex-idle-status)))

(defun my-hex-idle-status-off ()
  (interactive)
  (when (timerp my-hex-idle-timer)
    (cancel-timer my-hex-idle-timer)
    (setq my-hex-idle-timer nil)))

(defun int-to-binary-string (i)
  "convert an integer into it's binary representation in string format
By Trey Jackson, from https://stackoverflow.com/a/20577329/."
  (let ((res ""))
    (while (not (= i 0))
      (setq res (concat (if (= 1 (logand i 1)) "1" "0") res))
      (setq i (lsh i -1)))
    (if (string= res "")
        (setq res "0"))
    res))

(defun my-hex-idle-status ()
  (let ((word (thing-at-point 'word)))
    (when (string-prefix-p "0x" word)
      (let ((num (ignore-errors (string-to-number (substring word 2) 16))))
    (message "In binary: %s" (int-to-binary-string num))))))

Type M-x my-hex-idle-status-on to turn it on.

As noted, thanks to Trey Jackson for int-to-binary-string.