float、int、 byte、 short 类型数据的转换问题

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

#include<iostream>
#include<stdio.h>
#define uchar unsigned char
using 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 <process.h>
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<iostream>
#include<stdio.h>

using namespace std;

int main()
{
	float a = 17.625;
	short *b = (short *)&a;
	
	//此处需要注意,由于CPU架构不同,可能会采用不同的存储方式,也就是常说的大小端存储问题
	cout << " 高16: " << hex << b[1] << "      低16: " << hex <<b[0] <<endl;
	
	//在某些设备上运行此程序,可能会出现的情况是高16位和低16位整好相反
   //cout << " 高16: " << hex << b[0] << "      低16: " << hex <<b[1] <<endl;
   
	float *c = (float*)b;
	cout << *c << endl;
	//------------------------------------
	// 两个short型数据合成一个float
	short data[2];
	data[0]=b[0];
	data[1]=b[1];
	float *text_data = (float*)b;
	cout<<"合成测试:"<<*text_data<<endl;
	return 0;
}

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

#include <string>  

/**
 * 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;
}

猜你喜欢

转载自blog.csdn.net/qq_35608277/article/details/111875815