简体   繁体   English

如何将未签名的char缓冲区中的选择复制到另一个变量中并转换为int?

[英]How can I copy a selection from an unsigned char buffer into another variable and convert to int?

I have an unsigned char buffer which is being read in and working fine. 我有一个未签名的char缓冲区,正在读取并且可以正常工作。 I need to be able to select a number of bits within the main buffer and copy them to another variable to convert from hex data (little endian) into an integer to be displayed. 我需要能够在主缓冲区中选择一些位数,然后将它们复制到另一个变量中,以将十六进制数据(小尾数)转换为要显示的整数。 I cannot for the life of me get this working. 我一辈子都无法工作。 The following code prints the values I need in hex (in reverse order due to endianness) but I can't figure out how to use it. 下面的代码以十六进制(由于字节顺序相反)打印我需要的值,但是我不知道如何使用它。

void printFromBuffer(unsigned char *buffer, int block, int offset, int size){
    unsigned char *ptr = buffer;
    ptr += block * 0x10 + offset;
    for(int i=0;i<size;i++){
        printf("%X \n",ptr[i]);
    }
}

printFromBuffer(buffer, 0x08, 0x03, 0x02);

Thanks 谢谢

Ok, this code works but, I doubt this is the most efficient way of doing this. 好的,这段代码有效,但是,我怀疑这是最有效的方法。 If anyone else can clean this up to prevent future inefficiency then please go ahead. 如果其他人可以清理此文件以防止将来效率低下,请继续。

void printFromBuffer(unsigned char *buffer, int block, int offset, int size, string attribute){
    unsigned char *ptr = buffer;
    char p[255];
    string contents = "";
    unsigned int x;   
    std::stringstream ss;
    ptr += block * 0x10 + offset;
    for(int i=size;i--;){
        sprintf_s(p,"%02X",ptr[i]);
        contents += p;
    }
    ss << std::hex << contents;
    ss >> x;
    cout << attribute << ": " << x;
    printf("\n");
}

printFromBuffer(buffer, 0x08, 0x03, 0x02, "Serial");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM