views:

98

answers:

2

I am using following snippet to build a 32 bit integer to use with setRGB of BufferedImage


(bit-or (bit-shift-left a 24)
          (bit-or (bit-shift-left r 16)
              (bit-or (bit-shift-left g 8) b)))

after writing colors reading them back reveals wrong colors is there a fault in my logic?

+1  A: 

Are you sure you have a problem? I tried generating a few values based on your method and a functionally equivalent alternative:

 (defn argbval
  [a r g b]
  (bit-or (bit-shift-left a 24)
          (bit-or (bit-shift-left r 16)
              (bit-or (bit-shift-left g 8) b))))

(defn altargbval
  [a r g b]
  (+ (* 16777216 a) (* 65536 r) (* 256 g) b))

(defn -main
  ([& args]
    (println "(argbval 25 21 23 29): " (argbval 25 21 23 29))
    (println "(altargbval 25 21 23 29): " (altargbval 25 21 23 29))
    (println "(argbval 0 0 0 0): " (argbval 0 0 0 0))
    (println "(altargbval 0 0 0 0): " (altargbval 0 0 0 0))
    (println "(argbval 255 255 255 255): " (argbval 255 255 255 255))
    (println "(altargbval 255 255 255 255): " (altargbval 255 255 255 255))))

and got identical values.

(argbval 25 21 23 29):  420812573
(altargbval 25 21 23 29):  420812573
(argbval 0 0 0 0):  0
(altargbval 0 0 0 0):  0
(argbval 255 255 255 255):  4294967295
(altargbval 255 255 255 255):  4294967295

I got the same numbers on my pocket caculator.

Are there specific arguments that you have seen to produce incorrect results?

Perhaps it isn't a fault in this logic but in writing/reading the values to the BufferedImage.

clartaq
I jumped to the calculation that the problem was on my side but it was actually the image that had the problem.
Hamza Yerlikaya
+1  A: 

I keep a bytes-to-int function that converts a sequence of bytes into a number in my misc.clj:

(defn bytes-to-int [bytes] 
     (let [powers (iterate #(* % 256) 1)]
       (reduce + 0 (map * bytes powers))))

it comes handy fairly often.

Arthur Ulfeldt