C++笔记-char*存储的二进制转成long long十进制(读串口的时候经常用到)

    xiaoxiao2025-07-14  5

    目录

     

    背景

    概念及源码


     

     

    背景

    在读串口数据的时候,很多时间读取的是二进制数据,很多情况下都是uchar的数组,这数字一般比int(4字节)大比long long(8字节)小。

    如下例子:

    今天就在远程给客户敲代码,花了点时间,在此记录下。以后直接可以拷贝。

     

    概念及源码

    这里逻辑如下。

    把为满足64位的数据补充为64位。

    使用pow()进行累加。

    代码如下:

    #include <iostream> #include <math.h> using namespace std; int main(int argc, char *argv[]) { char *dataPtr = "1111111111111111"; cout << dataPtr << endl; string str = dataPtr; string fullStr; for(int i = 0; i < 8 * 8; i++) fullStr += "0"; fullStr += str; cout << fullStr << endl; long long data = 0; int lenth = fullStr.length(); const char *p = fullStr.c_str(); for(int i = 0; i < lenth; i++){ if(p[lenth - 1 - i] != '0'){ data += pow(2, i); } } cout << data << endl; return 0; }

    程序运行截图如下:

    第一行是原始数据。

    第二行是补充数据。

    最后一行是转10进制后的数据。

    换一串数据看看。

    最新回复(0)