> Dealing with byte-arrays, you will want to use the write-method that
> takes an array, not the one that takes a string.
>
> Constructing the array is a bit tricky:
>
> ; Define your int
> (def pix 652187261)
>
> ; Define your array, typed as array of char
> (def payload
> (into-array Character/TYPE [(char (bit-shift-right pix 16))
> (char (bit-shift-right pix 8))
> (char pix)]))
Char's on the JVM are not bytes, and are wider than 8 bits -- so if
you're packing binary data, you should use Byte and byte instead of
Character and char. (Note too that the pix value is greater than 2^24,
so you need four bytes to store it if you're using a byte-array.)
As wwmorgan mentioned, FileOutputStreams can write out byte-buffers,
so the following seems to work:
; Define your int
(def pix 652187261)
; Define your array, typed as array of byte (not char!)
(def payload
(into-array Byte/TYPE [(byte (bit-shift-right pix 24))
(byte (bit-shift-right pix 16))
(byte (bit-shift-right pix 8))
(byte pix)]))
; Create your FileWriter
(def ofile (java.io.FileOutputStream. "/tmp/somefile.bin2"))
; Write and close
(.write ofile payload)
(.close ofile)
The created file contains four bytes: 26 df 96 7d.
Bonus question for the bored reader: write a function,
(byte-array-maker N), that takes a width N, and returns a function
that takes an Integer as input and returns an N-width byte array
containing the Integer in big-endian order. E.g.
((byte-array-maker 4) 652187261)
=> [4-byte array: 26, df, 96, 7d]
Cheers,
Graham
It looks like with-open accepts any number of bindings. Does it just
call close on the first one when the body finishes or on all of them?
If I wanted to figure this out for myself, how would I find the source
code for with-open?
--
R. Mark Volkmann
Object Computing, Inc.
Hi,
If you're using Slime in Emacs, type in the word "with-open" (or put
your cursor on it in a Clojure source file) and press M-. (alt-period
or Escape, period).
Best,
Graham