Search code examples
c++pointers

How to create integer poiner in an array of raw data?


I have a file called "config", this file contains header data and int16_t value, the problem is that I can't create pointer to that integer to use it in my code.

    std::vector<char> Config;
    int16_t Config_Number = &Config[18];

Doing this gives an error "value of type "char" cannot be used to initialize entity of type "int16_t"".

Also I don't want to convert values because in ASM I can just load data into registers and do anything what I want.


Solution

  • I would probably do something like this:

    int16_t Config_Number = static_cast<int16_t>((config[18]<<8) | config[19]);
    

    Depending on endianess, you might need:

    int16_t Config_Number = static_cast<int16_t>((config[19]<<8) | config[18]);
    

    ...instead.

    You could use memcpy or memmove instead, but I don't think it accomplishes much (in this case).

    A bit of explanation:

    • reading and operating on individual chars from the array avoids any alignment issues.
    • The shift and | promote to int, so you probably want to explicitly narrow to int16_t before assigning (otherwise the compiler is likely to warning about a narrowing conversion).