将十进制浮点数转换为特殊十六进制表示法的更好方法
Better way to convert decimal float into special hexadecimal notation
我有 0 到 ~15.9 之间的十进制数,想将它们转换成特定的十六进制表示法。
所以特殊符号是这样的:
有 16 位。前 4 位用于小数点前的位置。接下来的 12 位用于小数位。
A * 16^0 + B * 16^{-1} + C * 16^{-2} + D * 16^{-3}
下面是我现在在 C++ 中的做法(我是“暴力破解”它。只需检查 16 适合 A 的频率,然后检查 1/16 适合 B 的频率等等):
uint16_t dec_to_special_hex(double x){
uint16_t A, B, C, D;
A = static_cast<uint16_t>(x);
if (A > 15)
return 65535;
double remainder = x - A; //get decimal places
B = static_cast<uint16_t>(remainder * 16);
remainder = remainder - B * (1 / 16);
C = static_cast<uint16_t>(remainder * 16 * 16);
remainder = remainder - C * (1 / (16 * 16));
D = static_cast<uint16_t>(remainder * 16 * 16 * 16);
remainder = remainder - D * (1 / (16 * 16 * 16));
uint16_t temp, ret = A;
ret = ret << 12;
temp = B << 8;
ret = ret | B;
temp = C << 4;
ret = ret | C;
ret = ret | D;
return ret;
}
如果没有更好、更优雅的方法来做到这一点,我会很伤心。我正在查看我正在处理的数字,感觉必须有更多的东西,但我还找不到更好的方法。
很高兴收到您的建议!
I wounder if there is no better, more elegant way to do this
优雅是主观的,但是:
您可以做的一件事是直接使用这些位。检查此 simple converter to see how IEEE floating point numbers work (if you don't know already). Then look at 以获取获取浮点数的不同位组的方法(其中的答案适用于 float
类型,但转换为 double
很简单)。
获得位后,您需要做的就是根据 指数 移动 尾数,然后执行位-明智的 &
与不同的 windows 以获得 A
、B
、C
和 D
.
的位
假设您只想截断而不是舍入,这可以通过以下方式完成:
uint16_t dec_to_special_hex(double x)
{
return
x < 0 ? 0 :
16 <= x ? 65535 :
4096*x;
}
我有 0 到 ~15.9 之间的十进制数,想将它们转换成特定的十六进制表示法。 所以特殊符号是这样的: 有 16 位。前 4 位用于小数点前的位置。接下来的 12 位用于小数位。
A * 16^0 + B * 16^{-1} + C * 16^{-2} + D * 16^{-3}
下面是我现在在 C++ 中的做法(我是“暴力破解”它。只需检查 16 适合 A 的频率,然后检查 1/16 适合 B 的频率等等):
uint16_t dec_to_special_hex(double x){
uint16_t A, B, C, D;
A = static_cast<uint16_t>(x);
if (A > 15)
return 65535;
double remainder = x - A; //get decimal places
B = static_cast<uint16_t>(remainder * 16);
remainder = remainder - B * (1 / 16);
C = static_cast<uint16_t>(remainder * 16 * 16);
remainder = remainder - C * (1 / (16 * 16));
D = static_cast<uint16_t>(remainder * 16 * 16 * 16);
remainder = remainder - D * (1 / (16 * 16 * 16));
uint16_t temp, ret = A;
ret = ret << 12;
temp = B << 8;
ret = ret | B;
temp = C << 4;
ret = ret | C;
ret = ret | D;
return ret;
}
如果没有更好、更优雅的方法来做到这一点,我会很伤心。我正在查看我正在处理的数字,感觉必须有更多的东西,但我还找不到更好的方法。 很高兴收到您的建议!
I wounder if there is no better, more elegant way to do this
优雅是主观的,但是:
您可以做的一件事是直接使用这些位。检查此 simple converter to see how IEEE floating point numbers work (if you don't know already). Then look at float
类型,但转换为 double
很简单)。
获得位后,您需要做的就是根据 指数 移动 尾数,然后执行位-明智的 &
与不同的 windows 以获得 A
、B
、C
和 D
.
假设您只想截断而不是舍入,这可以通过以下方式完成:
uint16_t dec_to_special_hex(double x)
{
return
x < 0 ? 0 :
16 <= x ? 65535 :
4096*x;
}