如何提取字节 [英] How to extract the bytes
本文介绍了如何提取字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们如何提取字节.例如,如果int
占用4个字节,则必须从中提取第1个字节或第3个字节.
How can we extract byte. For ex, if int
takes 4 bytes and from that I have to extract 1st byte or 3 rd byte. How we can do that?
推荐答案
一种优雅"的方式使用了union
:
An ''elegant'' way usesunion
:
union Mixed
{
int c;
unsigned char b[4];
};
int main()
{
int i;
union Mixed m;
m.c = 65535;
printf("int: %d.\n");
for (i=0; i<4; i++)
{
printf("byte[%d]: %d\n",i, m.b[i]);
}
}
您需要在位位置输入值.表示二进制值rt?
使用按位移位运算符可以做到这一点.
假设我是您的整数,您需要获取其第N位值.
请按照以下步骤进行操作
a =我右移(N-1)
b =右移I N
c =左移b 1. R = XOR c;
R是您的Nth位二进制值. 1或0
C函数可能看起来像下面的
You need value at the bit position. means a binary value rt?
this is possible using bitwise shift operator.
suppose I is your integer and you need to get its Nth bit value.
this possible by following steps
a = right shift I by (N-1)
b = right shift I by N
c = Left shift b by 1.
R = a XOR c;
R is your Nth Bit value in binary. either 1 or 0
c function may look liek below
int GetBit( int I, int N)
{
int a = I >> ( N - 1);
int b = I >> N;
b = b << 1;
int r = a ^ b;
return r;
}
而且这仅对N = 32无效.
您需要单独编写该逻辑.
希望这就是您要查找的内容
and this will not work only for N = 32.
that logic you need to write seprate.
Hope this is what you are looking for
您可以将字符指针指向整数变量,然后使用该指针获得所需的字节
函数看起来像这样
You can take a character pointer to the integer variable , and then using the pointer you can have the required byte
Function would look like this
char GetByteFrom( int i, int i_iByteIndex)
{
char * cPointer = (char*)&i;
return *(cPointer + i_iByteIndex);
}
这篇关于如何提取字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文