Click here to Skip to main content
15,902,198 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
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.
Posted
Updated 26-Jun-18 23:50pm
v4

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

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.
 
Share this answer
 
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):
C++
#define swap(v) ((((v) & 0x000F) << 12) | (((v) & 0xF000) >> 12) | ((v) & 0x0FF0))
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:
C++
#define swap(v) ((short int)((((v) & 0x000F) << 12) | (((unsigned)(v) & 0xF000) >> 12) | ((v) & 0x0FF0)))
 
Share this answer
 
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;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900