如何扭转4字节的无符号整数的? [英] How to reverse the 4 bytes of an unsigned integer?
本文介绍了如何扭转4字节的无符号整数的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用'«'和'»'扭转的无符号整数,位元与和OR(安培;和|),但无法弄清楚如何做到这一点<。 / p>
我已经有;
INT主(INT ARGC,字符** argv的){
无符号整型getal;
scanf函数(%i的,&安培; getal);
的printf(%X \\ n,getal);
返回0;
}
用户输入:现在0xaabbccdd,输出:AABBCCDD,它应该输出DDCCBBAA
我也试过;
INT主(INT ARGC,字符** argv的){
无符号整型getal;
无符号整数X;
scanf函数(%i的,&安培; getal);
INT I;
对于(I = 0; I&下; 32; ++ i的){
getal&所述;&下; = 1;
getal | =(X安培; 1);
X - GT;&GT; = 1;
的printf(%X \\ n,getal);
}
返回0;
}
但结果却是完全不同的。
解决方案
试试这个:
INT getal; //这是普通的整数
INT逆转; //这是getal反向/ *获取数字形式的控制台这里* /字符* N1,N2 *;
N1 =(字符*)及getal;
N2 =(字符*)及反;*(N 2 + 0)= *(N1 + 3); //或N2 [0] = N1 [3];
*(N + 1)= *(N1 + 2); //或N2 [1] = N1 [2];
*(N2 + 2)= *(N1 + 1); //或N2 [2] = N1 [1];
*(N 2 + 3)= *(N1 + 0); //或N2 [3] = N1 [0];/ *打印逆转这里* /
请注意: *(A + B)= A [B] = B [A]
I am trying to reverse the unsigned integer by using the '«' and '»', and bitwise 'AND' and 'OR' (& and |), but can't figure out how to do this.
What I already have;
int main(int argc, char** argv) {
unsigned int getal;
scanf("%i", &getal);
printf("%X\n", getal);
return 0;
}
User input: 0xaabbccdd, output now: AABBCCDD, what it should output DDCCBBAA
I also tried;
int main(int argc, char** argv) {
unsigned int getal;
unsigned int x;
scanf("%i", &getal);
int i;
for (i = 0; i < 32; ++i) {
getal <<= 1;
getal |= (x & 1);
x >>= 1;
printf("%X\n", getal);
}
return 0;
}
but the result was completely different.
解决方案
Try this:
int getal; // this is regular integer number
int reversed; // this is reverse of getal
/* get number form console here */
char *n1, *n2;
n1 = (char *)&getal;
n2 = (char *)&reversed;
*(n2 + 0) = *(n1 + 3); // or n2[0] = n1[3];
*(n2 + 1) = *(n1 + 2); // or n2[1] = n1[2];
*(n2 + 2) = *(n1 + 1); // or n2[2] = n1[1];
*(n2 + 3) = *(n1 + 0); // or n2[3] = n1[0];
/* print reversed here */
Note: *(a + b) = a[b] = b[a]
这篇关于如何扭转4字节的无符号整数的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文