Skip to content

Instantly share code, notes, and snippets.

@mauritslamers
Created November 23, 2009 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mauritslamers/241366 to your computer and use it in GitHub Desktop.
Save mauritslamers/241366 to your computer and use it in GitHub Desktop.
(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));
byteptr+=2;
}
return returnValues;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment