简体   繁体   English

从int64_t变量中提取八位字节

[英]extracting octects from int64_t variable

I want to extract number of octects from a int64_t variable. 我想从int64_t变量中提取八进制数。

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. 数组长度8足以存储提取的字节。
  • number_of_octets doesn't need to be explicitly passed. number_of_octets不需要显式传递。 You can calculate it using sizeof attribute . 您可以使用sizeof attribute进行计算。
  • Don't use typedef for uint8_t and uint64_t. 不要对uint8_t和uint64_t使用typedef。 Use #include <cstdint> (as suggested by Thomas Matthews). 使用#include <cstdint> (由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, " "));
}

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

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