这篇文章主要介绍“C/C++中double与byte数组互转的方法”,在日常操作中,相信很多人在C/C++中double与byte数组互转的方法问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”C/C++中double与byte数组互转的方法”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
本文包含了C/C++中byte(unsigned char)类型与double数组互转的方法,参见本文的最后两个方法,亲测可行。
#include <vector>
#include <iostream>
#include <string.h>
typedef unsigned char byte;
typedef struct {
int precession;
double value;
}ConstantValue;
byte int2Byte(int intVal);
void double2bytes(double data, byte* bytes);
double bytes2double(byte bytes[]);
std::vector<byte> convert2Byte(ConstantValue cv);
using namespace std;
/**
double convert to bytes
refers to struct body attribute
*/
int main(){
ConstantValue cv1, cv2;
cv1.precession = 10;
cv1.value = 36.32598;
cv2.precession = 15;
cv2.value = 271.15801;
vector<byte> cv1Byte = convert2Byte(cv1);
vector<byte> cv2Byte = convert2Byte(cv2);
for(int i = 0; i < cv1Byte.size(); i++){
cout<<"------"<<(int)cv1Byte[i]<<endl;
}
// byte dByte[8] = {58,16,64,0,0,0,0,0};
// cout<<"----double--"<<bytes2Double(dByte)<<endl;
byte b2[8] = {0x6E, 0x86, 0x1B, 0xF0, 0xF9, 0x21, 0x09, 0x40};
double fValue = 100.111;
byte bytes[8];
double2bytes(fValue, bytes);
/*
for(int i = 0; i < 8; i++){
cout<<"------"<<(int)bytes[i]<<endl;
}
byte b3[8] = {201, 118, 190, 159, 26, 7, 89, 64};
*/
byte arr[8];
copy(cv1Byte.begin()+3, cv1Byte.end(), arr);
cout<<"-----qqqqq-"<<bytes2double(arr)<<endl;
return 0;
}
vector<byte> convert2Byte(ConstantValue cv){
vector<byte> vecData;
vecData.push_back('I');//data type
vecData.push_back('N');//data type
vecData.push_back(int2Byte(cv.precession));//data type
// byte *valByte = double2bytes(cv.value);
byte valByte[8];
double2bytes(cv.value, valByte);
for(int i = 0; i < 8; i++){
vecData.push_back(valByte[i]);//data type
}
return vecData;
}
/**
* c++ double type length is 8 byte
*/
void double2bytes(double data, byte bytes[]){
int i;
char* p = (char*)&data;
for(i=0; i<8; i++)
{
bytes[i] = *p++;
}
}
/**
* convert byte array to double type
*/
double bytes2double(byte bytes[]){
double data = *((double *)bytes);
return data;
}
到此,关于“C/C++中double与byte数组互转的方法”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/3031930/blog/4546537