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

来源:百度知道 编辑:UC知道 时间:2024/06/06 11:29:13
即第一位和第八位,第二位和第七位。(要求不用循环)
其实我的用意是想减少算法的时间复杂度,并不是说只要不用for或者while就可以了
我想现在最好的算法也是象楼下说的4次 ,但不知道有没有什么好办法可以控制在3次以下(比如用异或,移位,取反等等)
kookhit的算法和用for语句基本上是没有区别的了,不过还是要谢谢你!

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

#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;
}

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

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

#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: ");