将 3D 矢量浮点打包到无符号 int 中并将其解压缩
Packed 3D vector float points into unsigned int and unpacked it
GetPacked会将一个3D点打包成一个无符号的int。我想把它解压缩回原点,但不起作用。请帮忙
uint32_t GetPacked(float x, float y, float z)
{
return ( 0xff000000
| ( ( uint32_t ) ( ( x * 127.5f ) + 127.5f ) << 16 )
| ( ( uint32_t ) ( ( y * 127.5f ) + 127.5f ) << 8 )
| ( ( uint32_t ) ( ( z * 127.5f ) + 127.5f ) ) );
}
越野车开箱
void UnPacked(uint32_t p, float* _x, float* _y, float* _z)
{
*_z = ( ( p & 0xff ) - 127.5f) / 127.5f;
p >>= 8;
*_y = ( ( ( p ) & 0xff ) - 127.5f) / 127.5f;
p >>= 8;
*_x = ( ( ( p ) & 0xff ) - 127.5f) / 127.5f;
}
谢谢
PS:我在 ideone 中创建了一个在线测试
你会失去精度。
// a, b, b in the range of -127.5 +127.5
uint32_t Code(float a, float b, float c)
{
union
{
uint32_t u32;
uint8_t u8[4];
} u;
u.u8[3] = 0xff;
u.u8[0] = a + 127.5f;
u.u8[1] = b + 127.5f;
u.u8[2] = c + 127.5f;
return u.u32;
}
void DeCode(uint32_t u32, float *a, float *b, float *c)
{
union
{
uint32_t u32;
uint8_t u8[4];
} u;
u.u32 = u32;
*a = (float)u.u8[0] - 127.5f;
*b = (float)u.u8[1] - 127.5f;
*c = (float)u.u8[2] - 127.5f;
}
int main(void)
{
float a = 102.3f, b = -56.4f, c = -126f, d,e,f;
uint32_t coded = Code(a, b, c);
DeCode(coded, &d, &e, &f);
printf("Original values: %f,%f,%f. Coded -%x. Decoded %f,%f,%fn", a, b, c, coded, d, e, f);
}
为了获得更好的精度,您可以将其缩放到 10 位。
#define B10MAX ((float)((1u << 10) - 1))
float Scale(float x)
{
return B10MAX * (x + 127.5f) / 255.0f;
}
float DeScale(unsigned x)
{
return 255.0f *(x) / B10MAX - 127.5f;
}
uint32_t Code10(float a, float b, float c)
{
union
{
uint32_t u32;
struct
{
uint32_t value1 : 10;
uint32_t value2 : 10;
uint32_t value3 : 10;
};
} u;
u.value1 = Scale(a);
u.value2 = Scale(b);
u.value3 = Scale(c);
return u.u32;
}
void DeCode10(uint32_t v, float *a, float *b, float *c)
{
union
{
uint32_t u32;
struct
{
uint32_t value1 : 10;
uint32_t value2 : 10;
uint32_t value3 : 10;
};
} u = {.u32 = v,};
*a = DeScale(u.value1);
*b = DeScale(u.value2);
*c = DeScale(u.value3);
}
在主要
coded = Code10(a, b, c);
DeCode10(coded, &d, &e, &f);
printf("Original values: %f,%f,%f. Coded = %x. Decoded %f,%f,%fn", a, b, c, coded, d, e, f);
相关文章:
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 从 std::vector<无符号字符>切片中提取 int?
- 是什么导致了这种使用三进制而不是短整型的有符号int到无符号int转换
- C++无符号短裤的划分导致 int
- 将无符号转换为复杂<int>原因符号转换警告
- 如何解决隐式转换丢失整数精度:'size_t'(又名"无符号长")到'int'警告?
- 无符号的 int 到有效数字
- C++:使用没有位移位的指针将无符号字符转换为无符号 int
- 整数类型应该显式转换(例如"int"到"无符号")还是只会增加混乱?
- 有没有办法在C++中将mpz_t转换为 int 或无符号长 int?
- 是否可以将无符号 int 的最大值转换为 int 并将结果转换为 -1?
- 为什么QByteArray的大小是"int"而不是"无符号int"
- 为什么 (-i) 的类型(其中 i 是无符号的 int)仍然是无符号的 int?
- 无符号长整型和无符号 int 之间有什么区别,这 2 种类型应该如何在 c# 中封送?
- 如何对无符号长 int 进行位掩码?
- 使用无符号int作为二进制来在c++中实现一个集
- 这个右移是如何工作的:字符串流>>无符号的int>>无符号的int?
- 转换 int -> 无符号长 长 是否由标准定义
- 为什么在执行 int / 无符号 int 除法时使用 'divl'