[英]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
*/
sizeof attribute
. sizeof attribute
进行计算。 #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.