本文介绍了转换浮动为unsigned long访问浮动内部,在C#定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要一个浮动转换为无符号长,同时保持二进制重新presentation在浮动(所以我做的的希望蒙上 5.0 5 !)。

I want to convert a float to a unsigned long, while keeping the binary representation of the float (so I do not want to cast 5.0 to 5!).

这是很容易在下面的方法做:

This is easy to do in the following way:

float f = 2.0;
unsigned long x = *((unsigned long*)&f)

不过,现在我需要做同样的事情在的#define ,因为我想在某些数组初始化(这样的[在线]功能以后使用是不是一种选择)。

However, now I need to do the same thing in a #define, because I want to use this later on in some array initialization (so an [inline] function is not an option).

这不会编译:

#define f2u(f) *((unsigned long*)&f)

如果我把它称为是这样的:

If I call it like this:

unsigned long x[] = { f2u(1.0), f2u(2.0), f2u(3.0), ... }

我得到的错误是(逻辑):

The error I get is (logically):

lvalue required as unary ‘&’ operand


注意:一个解决方案,建议下面是使用联盟键入我的数组。然而,这是没有选择。我实际上做以下内容:


Note: One solution that was suggested below was to use a union type for my array. However, that's no option. I'm actually doing the following:

#define Calc(x) (((x & 0x7F800000) >> 23) - 127)
unsigned long x[] = { Calc(f2u(1.0)), Calc(f2u(2.0)), Calc(f2u(3.0)), ... }

因此​​,阵列真的会/类型必须为长[]

推荐答案

您应该使用一个联盟:

union floatpun {
    float f;
    unsigned long l;
};

union floatpun x[3] = { {1.0}, {2.0}, {3.0} };

或者

union {
    float f[3];
    unsigned long l[3];
} x = { { 1.0, 2.0, 3.0 } };

(后者将让你通过 XL ,你需要类型的数组无符号长[3]

(The latter will let you pass x.l where you need an array of type unsigned long [3]).

当然,你需要确保无符号长浮动有你的平台上相同的大小。

Of course you need to ensure that unsigned long and float have the same size on your platform.

这篇关于转换浮动为unsigned long访问浮动内部,在C#定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 14:12