Frage

Here's the behavior I want:

user> (bit-get 4 2)
> 1

I know this could super easily be done using bit-test, i.e.:

(defn bit-get [x n]
  (if (bit-test x n) 1 0))

But I'm curious if there's anything already out there. It might be kind of petty of me, but it just seems sub-optimal (however minimally so) to have to test whether something is 0 or 1, and then return wehther or not it's 0 or 1 based on that test. So, I'd also be happy to hear of any ways to cut-out the middle man here, regardless of whether or not there's any previously-made bit-get function out there in the Clojure or Java world. Or perhaps I'm mistaken in the first place, and something about compilation or run-time optimization makes my bit-get function above not actually have to run the test just to return the value it's testing on? Or--seeing as I know next to nothing about timing/speed optimization involved in bitwise operators--perhaps it only seems sub-optimal, but is actually the fastest way to do it for some reason?

War es hilfreich?

Lösung

Can't say anything about optimization by the compiler (although I would be surprised if it was able to change a lot about your bit-get code), but - to take matters into your own hands - you could just rely on the lower-level logical operations bit-shift-right and bit-and, e.g.:

(defn bit-get [x n]
  (bit-and (bit-shift-right x n) 1))
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top