C语言 对字节的高位和低位进行互换!

2025-05-09 01:56:13
推荐回答(5个)
回答1:

可以直接用位运算:按位与,按位或,移位等

#include "stdio.h"
int main()
{
unsigned char tmp1,tmp2;

printf("please input a char: ");
scanf("%c", &tmp1);
tmp2=
((tmp1&0x01)<<7)
|((tmp1&0x02)<<5)
|((tmp1&0x04)<<3)
|((tmp1&0x08)<<1)
|((tmp1&0x10)>>1)
|((tmp1&0x20)>>3)
|((tmp1&0x40)>>5)
|((tmp1&0x80)>>7);
printf("converted char is: %c\n", tmp2);
return 0;
}

回答2:

可以直接用位运算:按位与,按位或,移位等
#include
"stdio.h"
int
main()
{
unsigned
char
tmp1,tmp2;
printf("please
input
a
char:
");
scanf("%c",
&tmp1);
tmp2=
((tmp1&0x01)<<7)
|((tmp1&0x02)<<5)
|((tmp1&0x04)<<3)
|((tmp1&0x08)<<1)
|((tmp1&0x10)>>1)
|((tmp1&0x20)>>3)
|((tmp1&0x40)>>5)
|((tmp1&0x80)>>7);
printf("converted
char
is:
%c\n",
tmp2);
return
0;
}

回答3:

#include "stdio.h"

struct bits_t
{
char b1:1;
char b2:1;
char b3:1;
char b4:1;
char b5:1;
char b6:1;
char b7:1;
char b8:1;
};
union u_cache
{
char c;
struct bits_t ch;
};

int main()
{
union u_cache tmp1,tmp2;

printf("please input a char: ");
scanf("%c", &tmp1.c);

tmp2.ch.b1 = tmp1.ch.b8;
tmp2.ch.b2 = tmp1.ch.b7;
tmp2.ch.b3 = tmp1.ch.b6;
tmp2.ch.b4 = tmp1.ch.b5;
tmp2.ch.b5 = tmp1.ch.b4;
tmp2.ch.b6 = tmp1.ch.b3;
tmp2.ch.b7 = tmp1.ch.b2;
tmp2.ch.b8 = tmp1.ch.b1;

printf("converted char is: %c\n", tmp2.c);

return 0;
}

回答4:

按位交换也就4次
可以不用循环

回答5:

赞成 高经理 的回答。
他的做法的对的。