Easiest way to get a byte array from a long is probably
(defn num->bytes [n] (.toByteArray (biginteger n)))
But, since your edit specifies you are using DataOutputStream
, just use the writeLong method, directly.
so.core=>(def buffer (java.io.ByteArrayOutputStream.))
#'so.core/buffer
so.core=> (def data-stream (java.io.DataOutputStream. buffer))
#'so.core/data-stream
so.core=> (.writeLong data-stream 257)
nil
so.core=> (.toByteArray buffer)
#<byte[] [B@6ea4b78b>
so.core=> (vec *1)
[0 0 0 0 0 0 1 1]
Problem with your code is as you diagnosed in your edit. You need the modulus over number of possible byte values, 256, rather than the maximum signed value, 128. Otherwise, you are mapping two byte-values to the same number (= (mod 127 128) (mod -1 128)) ;=> true
. Conversion to bytes will be signed (.byteValue (mod 255 256)) ;=> -1
.