Reputation: 5167
The byte 0xea
is equal to 234 in base 10. In Python, bytes are represented using unsigned integers, but in Java, they are signed, two's complement integers.
For example, in Java, if I cast (byte)234
, I get the signed integer -22
. When I use those bytes in a MessageDigest
, I get the same exact hash output as when I use the unsigned 234
in python. So I am confident that these represent the same byte.
However, in Clojure, the function (byte 234)
should cast to -22
, but instead it throws a clojure.lang.RT.byteCast
exception.
How can I cast integers to bytes in Clojure?
Upvotes: 2
Views: 1037
Reputation: 16194
You should use unchecked-byte
when it's OK to overflow:
(unchecked-byte 234)
=> -22
FYI it's also possible to toggle the default behavior with the *unchecked-math*
binding:
(set! *unchecked-math* true)
=> true
(byte 234)
=> -22
But you probably want to constrain this non-default behavior to the smallest scope possible.
Upvotes: 3