How to wrap on overflow when transfer a double to integer

17 ビュー (過去 30 日間)
Alex
Alex 2020 年 1 月 30 日
コメント済み: Alex 2020 年 2 月 1 日
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?

採用された回答

James Tursa
James Tursa 2020 年 1 月 30 日
編集済み: James Tursa 2020 年 1 月 30 日
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 件のコメント
James Tursa
James Tursa 2020 年 1 月 31 日
編集済み: James Tursa 2020 年 1 月 31 日
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 2020 年 2 月 1 日
Dear James Tursa,
Thank you for your help. It works.
Regards

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeOperators and Elementary Operations についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by