基础笔记1 —— float型数据与其他类型数据的转换问题
发布日期:2021-07-01 04:04:04 浏览次数:3 分类:技术文章

本文共 2480 字,大约阅读时间需要 8 分钟。

文章目录

不多说,直接上代码。

1.查看 float 型数据在内存中的二进制存储形式

#include
#include
#define uchar unsigned charusing namespace std;void binary_print(uchar c){
for (int i = 0; i < 8; ++i) {
if ((c << i) & 0x80) cout << '1'; else cout << '0'; } cout << ' ';}void main(){
float a; uchar c_save[4]; uchar i; void *f; f = &a; cout << "请输入一个浮点数:"; cin >> a; cout << endl; for (i = 0; i<4; i++) {
c_save[i] = *((uchar*)f + i); } cout << "此浮点数在计算机内存中储存格式如下:" << endl; for (i = 4; i != 0; i--) binary_print(c_save[i - 1]); cout << endl;}

2.float类型数据与十六进制的转换

#include 
int main(){
// 将十六进制转换为float形式 unsigned char pMem[] = {
0x66,0xE6,0xF0,0x42 }; float *p = (float*)pMem; printf("%g\r\n", *p); // 将float转换为16进制 float a = 120.45f; unsigned char * b = (unsigned char*)&a; for (int i = 0; i < 4; i++) printf("0x%2X,", b[i]); system("pause"); return 0;}

3.float型数据拆分成2个short型数据并还原

// Author:Jack Soong#include
#include
using namespace std;int main(){
float a = 17.625; short *b = (short *)&a; //此处需要注意,由于CPU架构不同,可能会采用不同的存储方式,也就是常说的大小端存储问题 cout << " 高16: " << hex << b[1] << " 低16: " << hex <
<

4.在C++中byte与int的互相转换

#include 
/** * htonl 表示 host to network long ,用于将主机 unsigned int 型数据转换成网络字节顺序; * htons 表示 host to network short ,用于将主机 unsigned short 型数据转换成网络字节顺序; * ntohl、ntohs 的功能分别与 htonl、htons 相反。 */ /** * byte 不是一种新类型,在 C++ 中 byte 被定义的是 unsigned char 类型; * 但在 C# 里面 byte 被定义的是 unsigned int 类型 */typedef unsigned char byte;/** * int 转 byte * 方法无返回的优点:做内存管理清爽整洁 * 如果返回值为 int,float,long,double 等简单类型的话,直接返回即可 * 总的来说,这真心是一种很优秀的方法设计模式 */void int2bytes(int i, byte* bytes, int size = 4);// byte 转 int int bytes2int(byte* bytes, int size = 4);void int2bytes(int i, byte* bytes, int size) {
// byte[] bytes = new byte[4]; memset(bytes, 0, sizeof(byte) * size); bytes[0] = (byte)(0xff & i); bytes[1] = (byte)((0xff00 & i) >> 8); bytes[2] = (byte)((0xff0000 & i) >> 16); bytes[3] = (byte)((0xff000000 & i) >> 24);}int bytes2int(byte* bytes, int size) {
int iRetVal = bytes[0] & 0xFF; iRetVal |= ((bytes[1] << 8) & 0xFF00); iRetVal |= ((bytes[2] << 16) & 0xFF0000); iRetVal |= ((bytes[3] << 24) & 0xFF000000); return iRetVal;}

  1. https://www.cnblogs.com/shangbolei/p/4441946.html

  2. https://blog.csdn.net/renanrenan/article/details/83094956

  3. https://www.cnblogs.com/java20130723/p/3212023.html

转载地址:https://miracle.blog.csdn.net/article/details/92778114 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:基础笔记3 —— 关于大小端数据存储方式的转换及测试说明
下一篇:数据类型在内存中的存储

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2024年05月01日 10时26分08秒