字节内高低位互换

kuaipian4724 2018-06-07 08:52:21
如题,AE007845转换为EA008754,C++如何实现
...全文
1423 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
#define HALFBYTE_SWAP(x) (((unsigned int)(x) >> 4) & 0x0f0f0f0f | ((x) << 4) & 0xf0f0f0f0)
自信男孩 2018-06-08
  • 打赏
  • 举报
回复
#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

int main()
{
    unsigned int    a = 0xAE007845, b, i;

    char buf[16], ch;
    snprintf(buf, sizeof(buf), "%X", a);

    for (i = 0; i < strlen(buf) - 1; i += 2) {
        ch = buf[i];
        buf[i] = buf[i+1];
        buf[i+1] = ch;
    }

    cout<<buf<<endl;
    sscanf(buf, "%X", &b);

    printf("%X --> %X\n", a, b);
    cout<<a<<b<<endl;

    return 0;
}
作为一个参考吧 方法可能多种,具体用哪种要根据实际使用场景。
wang0635 2018-06-08
  • 打赏
  • 举报
回复
#include<stdio.h>

unsigned int myswap(unsigned int x);

int main()
{
    unsigned int	a = 0xAE007845, b;
    b = myswap(a);
    printf("a=%x, b=%x\n", a, b);
    return 0;
}

unsigned int myswap(unsigned int x)
{
	int		i, size = sizeof(x);
	unsigned int	result;
	char	*px = (char *)&x, *pr = (char *)&result;
	for (i = 0; i < size; i++)
		pr[i] = (px[i] & 0x0f) << 4 | (px[i] & 0xf0) >> 4;
	return result;
}

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧