Prob = *((unsigned short*)(Prob));
Prob = (unsigned short)(Prob);
这对我没有用。如何正确转换?
答案 0 :(得分:1)
您面临的最大问题是那些超过USHRT_MAX
的双倍值。其次,您需要解决四舍五入问题。解决.5
上的舍入和设置舍入的简单方法可能类似于以下内容,其中函数array_dbl2short
返回成功转换为unsigned short
的double值的数量:
size_t array_dbl2short (unsigned short *usa, double *da, size_t n)
{
if (!usa || !da || !n) return 0;
register size_t i, ncnvt = 0;
for (i = 0; i < n; i++) {
if (da[i] < 0 || (unsigned long long)(da[i] + 0.5) > USHRT_MAX)
fprintf (stderr, "error: %lf outside range for conversion.\n",
da[i]);
else
usa[ncnvt++] = (unsigned short)(da[i] + 0.5);
}
return ncnvt;
}
使用它的一个简短例子是:
#include <stdio.h>
#include <limits.h>
size_t array_dbl2short (unsigned short *usa, double *da, size_t n);
int main (void) {
double arr[] = { 1.49, 1.5, 65535.49, 65535.5, -1.9, 25671.8 };
size_t i, n, nelem = sizeof arr/sizeof *arr;
unsigned short usarr[nelem];
if ((n = array_dbl2short (usarr, arr, nelem))) {
printf ("\n unsigned short array:\n\n");
for (i = 0; i < n; i++)
printf (" usarr[%zu] : %hu\n", i, usarr[i]);
}
return 0;
}
size_t array_dbl2short (unsigned short *usa, double *da, size_t n)
{
if (!usa || !da || !n) return 0;
register size_t i, ncnvt = 0;
for (i = 0; i < n; i++) {
if (da[i] < 0 || (unsigned long long)(da[i] + 0.5) > USHRT_MAX)
fprintf (stderr, "error: %lf outside range for conversion.\n",
da[i]);
else
usa[ncnvt++] = (unsigned short)(da[i] + 0.5);
}
return ncnvt;
}
(注意: double
值的实部必须能够表示为unsigned long long
,以便转换验证为工作正常)
示例使用/输出
$ ./bin/dbl2ushort
error: 65535.500000 outside range for conversion.
error: -1.900000 outside range for conversion.
unsigned short array:
usarr[0] : 1
usarr[1] : 2
usarr[2] : 65535
usarr[3] : 25672
此解决方案无法解决所有可能的舍入和转换问题。您还可以使用math.h
中的函数(例如modf
,round
等)来预制实部和舍入。如果您还有其他问题,请与我们联系。
答案 1 :(得分:0)
您需要显式转换每个值:
unsigned short * doubleToUShort(double * Prob_double, size_t N) {
unsigned short * Prob = malloc(sizeof(unsigned short) * N);
size_t i = 0;
for (i = 0; i < N; i++) {
Prob[i] = Prob_double[i];
}
return Prob;
}
那将向零转。如果您想要舍入到最近,可以使用#include <math.h>
并将该循环更改为
for (i = 0; i < N; i++) {
Prob[i] = round(Prob_double[i]);
}