0

I have an unsigned char buffer which is being read in and working fine. 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

4

1 回答 1

0

好的,这段代码有效,但我怀疑这是最有效的方法。如果其他人可以清理它以防止将来效率低下,那么请继续。

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");
于 2013-08-12T02:56:31.790 回答