如何获得一个变量的各字节的值? [英] How to get the value of individual bytes of a variable?
本文介绍了如何获得一个变量的各字节的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道,让一个变量的类型使用的字节数,你可以使用的sizeof(INT)
的实例。你如何使用的各个字节的值,当您存储与该变量的类型是多少? (即 INT X = 125
)
I know that to get the number of bytes used by a variable type, you use sizeof(int)
for instance. How do you get the value of the individual bytes used when you store a number with that variable type? (i.e. int x = 125
.)
推荐答案
您可以通过使用一些指针运算得到字节:
You can get the bytes by using some pointer arithmetic:
int x = 12578329; // 0xBFEE19
for (size_t i = 0; i < sizeof(x); ++i) {
// Convert to unsigned char* because a char is 1 byte in size.
// That is guaranteed by the standard.
// Note that is it NOT required to be 8 bits in size.
unsigned char byte = *((unsigned char *)&x + i);
printf("Byte %d = %u\n", i, (unsigned)byte);
}
在我的机器上(英特尔的x86-64),输出是:
On my machine (Intel x86-64), the output is:
Byte 0 = 25 // 0x19
Byte 1 = 238 // 0xEE
Byte 2 = 191 // 0xBF
Byte 3 = 0 // 0x00
这篇关于如何获得一个变量的各字节的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文