3

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.

DrLock
  • 43
  • 4
  • Out of curiousity: why write 0xE7 rather than 0b11100111, then? – Stefan Nov 26 '14 at 18:23
  • Good idea, but "0b" notation is [not standard C](http://stackoverflow.com/questions/15114140/writing-binary-number-system-in-c-code) and my compiler doesn't support it. – DrLock Nov 26 '14 at 18:44

1 Answers1

3

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.

Community
  • 1
  • 1
legoscia
  • 39,593
  • 22
  • 116
  • 167
  • 2
    That is what I needed, thank you! By the way, this is just a little bit prettier: (defun int-to-binary-string (i) "convert an integer into it's binary representation in string format By Trey Jackson, from http://stackoverflow.com/a/20577329/." (let ((res "") (cnt 0)) (while (not (= i 0)) (setq res (concat (if (= 1 (logand i 1)) "1" "0") res)) (setq i (lsh i -1)) (if (= cnt 3) (setq res (concat " " res))) (setq cnt (+ cnt 1)) ) (if (string= res "") (setq res "0")) res)) – DrLock Nov 26 '14 at 19:02