How to wrap on overflow when transfer a double to integer
28 views (last 30 days)
Show older comments
I would like to transfer a double to an unsigned integer, specific 16-bit integer, with WRAP on overflow in Matlab coding.
I currently use, but it SATURATEs on overflow
y = uint16(x);
Does anyone have solution?
0 Comments
Accepted Answer
James Tursa
on 30 Jan 2020
Edited: James Tursa
on 30 Jan 2020
You could use:
y = mod(x,double(intmax('uint16'))+1);
But, if x is too large so that eps(x) > 1 the result might be somewhat meaningless.
7 Comments
James Tursa
on 31 Jan 2020
Edited: James Tursa
on 31 Jan 2020
Sorry. I just gave you the gist of the code, not the complete code. A complete mex file would be:
(EDIT: Updated code to account for mwSize possibly being different size than size_t)
/* Convert a full real double input to a uint16 output with natural mod conversion */
#include "mex.h"
#include <stdint.h>
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
double *d;
uint16_t *u;
size_t n, ndims;
size_t *sdims;
mwSize *mdims;
if( nrhs != 1 || !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) ) {
mexErrMsgTxt("Need exactly one full real double input");
}
if( nlhs > 1 ) {
mexErrMsgTxt("Too many outputs");
}
ndims = mxGetNumberOfDimensions(prhs[0]);
mdims = (mwSize *) mxGetDimensions(prhs[0]);
sdims = (size_t *) mxMalloc(ndims*sizeof(*sdims));
for( n = 0; n<ndims; n++ ) {
sdims[n] = mdims[n];
}
plhs[0] = mxCreateUninitNumericArray(ndims, sdims, mxUINT16_CLASS, mxREAL);
mxFree(sdims);
d = (double *) mxGetData(prhs[0]);
u = (uint16_t *) mxGetData(plhs[0]);
n = mxGetNumberOfElements(prhs[0]);
while( n-- ) {
*u++ = *d++;
}
}
More Answers (0)
See Also
Categories
Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!