How to wrap on overflow when transfer a double to integer

13 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

James Tursa
James Tursa il 30 Gen 2020
Modificato: James Tursa il 30 Gen 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 Commenti
James Tursa
James Tursa il 31 Gen 2020
Modificato: James Tursa il 31 Gen 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++;
}
}
Alex
Alex il 1 Feb 2020
Dear James Tursa,
Thank you for your help. It works.
Regards

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Operators and Elementary Operations in Help Center e File Exchange

Prodotti

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by