宏交换字节的BYTE源代码 [英] Macro to swap nibble of BYTE source code

查看:153
本文介绍了宏交换字节的BYTE源代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我在接受采访时问了一个问题。



你能不能请帮我解决这个问题。



提前感谢。



我是什么尝试过:



Hi all,

I was asked by a question in a interview.

could you please help me out in solving this question.

thanks in advance.

What I have tried:

Hi all,

I was asked by a question in a interview.

could you please help me out in solving this question.

thanks in advance.

推荐答案

宏不是一个函数。阅读两者的比较,了解差异。

A macro isnt a function. Read the comparison of both to learn the differences.
#define SWAPNIBBLES(c) ( (c << 4) + (c >> 4) } 



我不喜欢宏,因为它们不可调试,编译器可以优化函数,甚至比宏更好。使用宏编程是在80年代。


I dont like macros because they arent debuggable and the compiler can optimize functions as good or even better than macros. Using macro is programming in the 80s.


它是相似的。只需使用适当的掩码(0x000F和0xF000)和shift(12)来交换16位值的最高和最低半字节。但是不要忘记让中间位不变(也返回它们):

It is similar. Just use the appropriate masks (0x000F and 0xF000) and shifts (12) to swap the highest and lowest nibble of a 16 bit value. But don't forget to let the middle bits untouched (return them too):
#define swap(v) ((((v) & 0x000F) << 12) | (((v) & 0xF000) >> 12) | ((v) & 0x0FF0))

因为赋值是使用宏而这些不知道传递参数的类型,它还需要添加ac得到所需的结果并为右移转换操作数以执行无符号转移:

Because the assignment is to use a macro and these don't know about the type of the passed argument, it requires also adding a cast to get the desired short result and casting the operand for the right shift to perform an unsigned shift:

#define swap(v) ((short int)((((v) & 0x000F) << 12) | (((unsigned)(v) & 0xF000) >> 12) | ((v) & 0x0FF0)))


无论是16位还是32位还是64位处理器都可以工作

Will work whether 16 bit or 32 bit or 64 bit processor
#include<stdio.h>
#define HALFWIDTH() (sizeof(short int) << 2)
#define BITSWAP(p)     (unsigned short)(p << HALFWIDTH()) | (unsigned short)(p >> HALFWIDTH())
int main() {
  unsigned short i;
  printf("half short: %d\n", HALFWIDTH());
  printf("read the number: \n");
  scanf("%hu", &i);
  printf("shift left: %hu\n", (unsigned short)(i << HALFWIDTH()));
  printf("shift right: %hu\n", (unsigned short)(i >> HALFWIDTH()));
  printf("%hu\n", BITSWAP(i));
  return 0;
}


这篇关于宏交换字节的BYTE源代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆