简体   繁体   中英

extracting octects from int64_t variable

I want to extract number of octects from a int64_t variable.

The code so far I have come up is below, but it is not storing the correct values in the data array:

typedef unsigned char uint8_t;
typedef long long int64_t;


uint8_t* extractOctets(int64_t& attribute, int number_of_octets)
{
    uint8_t data[257];
    for (int i = 0; i < number_of_octets; i++)
    {
        data[i++] = (uint8_t) (attribute >> (8 * i));
    }
    return data;
}

/*
I want to store the octets in this order.
data[0] = high_octet
data[1] = middle_octet
.
.
.
data[number_of_octets-1] = low_octet
*/
  • You're returning a pointer to a local variable. Either declare data in the calling code or allocate memory for it.
  • Array length 8 is enough to store the extracted bytes.
  • number_of_octets doesn't need to be explicitly passed. You can calculate it using sizeof attribute .
  • Don't use typedef for uint8_t and uint64_t. Use #include <cstdint> (as suggested by Thomas Matthews).

The following changes achieve what you need. Note I tried to stick close to your original interface, but I did have to change it somewhat due to problems with it. Here I have the octet array provided as an output parameter (your solution above doesn't work as you're trying to return a pointer to a function local variable). There are plenty of other (and perhaps better) ways to solve it, but this sticks reasonably close to your design.

void extractOctets(int64_t& attribute, uint8_t (&octets)[sizeof(int64_t)])
{
    for (int i = 0; i < sizeof(int64_t); i++)
    {
        octets[i] = (uint8_t) (attribute >> (8 * (7 - i)));
    }
}

int main()
{
    int64_t attr = (1 << 7) + (1 << 15);
    uint8_t octets[8];

    extractOctets(attr, octets);

    std::copy(std::begin(octets), std::end(octets), std::ostream_iterator<int>(std::cout, " "));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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