Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
(defn float-to-two-bytes [value]
(let [ dblval (double value) intval (int (* dblval 32765)) ]
(if (and (>= dblval -1 ) (<= dblval 1))
[ (byte intval) (byte (bit-shift-right intval 8)) ])))
(defn convert-float-to-byte-array [floatseq]
(into-array Byte/TYPE
(reduce conj []
(mapcat #(float-to-two-bytes %) floatseq))))
public byte[] convertDoubleArrayToByte(double[] incoming){
// This function converts an array of double precision samples into their byte array counterpart.
// as with its collegue (the convertByteArrayToDouble function) it could be used for other purposes than
// just working with buffers the size of the DSP buffer, so it keeps track of its own incoming and outgoing
// array sizes.
int numberofoutgoingbytes = incoming.length << 1; // *2
int numberofincomingdoubles = incoming.length;
byte[] returnValues = new byte[numberofoutgoingbytes];
short sample_as_int;
int[] result = new int[numberofincomingdoubles];
int byteptr = 0;
for(int i=0;i<numberofincomingdoubles;i++){
sample_as_int = (short)Math.round(32767.0 * incoming[i]);
returnValues[byteptr] = (byte)(sample_as_int & 0xFF);
returnValues[byteptr+1] = (byte)((sample_as_int >> 8) & 0xFF);
// the bitshifting trick above is much faster, but does the same as the following calculation
//byte a = (byte)((sample_as_int/256));
//byte b = (byte)(sample_as_int-(256*a));
return returnValues;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.