将double数组转换为unsigned short? [英] Convert a double array to unsigned short?
问题描述
Prob = *((unsigned short*)(Prob));
Prob = (unsigned short)(Prob);
这对我不起作用。如何正确转换它?
This didn't work for me. How to convert it correctly?
推荐答案
您面临的最大问题是那些超过 USHRT_MAX的双精度值
。其次,您需要解决舍入问题。解决这两个问题并在 .5
中设置舍入的简单方法可能类似于以下内容,其中函数 array_dbl2short
返回成功转换为 unsigned short
的双精度值数目:
The biggest issue you face is for those double values that exceed USHRT_MAX
. Secondarily, you need to address rounding. A simple approach that addresses both and sets rounding at .5
could look something like the following where the function array_dbl2short
returns the number of double values successfully converted to unsigned short
:
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;
}
(注意: real- double
值的一部分必须能够表示为 unsigned long long
以便进行转换验证才能正常工作)
(note: the real-part of the double
values must be capable of being expressed as an unsigned long long
for the conversion validations to work properly)
示例使用/输出
$ ./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
等)执行实部和舍入。如果您还有其他问题,请告诉我。
This solution doesn't address all possible rounding and conversion issues. You can also use the function in math.h
(e.g. modf
, round
, etc) to preform the real-part and rounding. Let me know if you have further questions.
这篇关于将double数组转换为unsigned short?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!