如何将浮动转换为在C 4字节字符? [英] How to convert a float to a 4 byte char in C?

查看:127
本文介绍了如何将浮动转换为在C 4字节字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转换一个浮点数,例如2.45到4字节的字符数组。
因此,2.45应该是这样的'@'FS我我这是二进制的IEEE重新presentation 2.45 = 01000000 00011100 11001100 11001101

I want to convert a float number for example 2.45 to the 4 byte char array. so the 2.45 should look like this '@' 'FS' 'Ì' 'Í' which is binary the ieee representation of 2.45 = 01000000 00011100 11001100 11001101?

我已经解决了这个问题,但它有一个不好的复杂性。你有什么好主意?

I've solved the problem but it has a bad complexity. do you have any good ideas?

谢谢你的好答案。

可以请你告诉我的方式从字符数组的浮点数回来?

can you please tell me the way back from the char array to the float number ?

推荐答案

您必须这样做,包括几个方面,这些二:

You have a few ways of doing this, including these two:


  1. 使用类型转换和指针:

  1. Use typecasting and pointers:

float f = 2.45;
char *s = (char *) &f;

请注意,这是不以任何方式安全的,有字符串后无字符串结束。

Note that this isn't safe in any way and that there is no string terminator after the "string".

使用联盟

union u
{
    float f;
    char s[sizeof float];
};

union u foo;
foo.f = 2.45;

的字符数组现在可以访问来获取字节值。还要注意像第一种选择是没有字符串结束。

The char array can now be accessed to get the byte values. Also note like the first alternative there is no string terminator.

这篇关于如何将浮动转换为在C 4字节字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆