Skip to content

Instantly share code, notes, and snippets.

@17twenty
Created January 28, 2015 10:31
Show Gist options
  • Save 17twenty/4626d76436f8c4a61695 to your computer and use it in GitHub Desktop.
Save 17twenty/4626d76436f8c4a61695 to your computer and use it in GitHub Desktop.
Bitshifting Source and Header
#include <stdio.h>
#include "bitshift.h"
int main()
{
unsigned char ascii_char = 'A'; /* char = 8 bits only */
int test_nbr = 10;
printf("Starting character = %08X\n", ascii_char);
/* The 5th bit position determines if the character is
uppercase or lowercase.
5th bit = 0 - Uppercase
5th bit = 1 - Lowercase */
printf("\nTurn 5th bit on = %08X\n", SET_FLAG(ascii_char, BIT_POS(5)) );
printf("Turn 5th bit off = %08X\n\n", CLR_FLAG(ascii_char, BIT_POS(5)) );
printf("Look at shifting bits\n");
printf("=====================\n");
printf("Current value = %08X - %d\n", test_nbr, test_nbr);
test_nbr = BIT_SHIFTL(test_nbr, 1);
printf("Shifting one position left = %80X - %d\n", test_nbr, test_nbr);
test_nbr = BIT_SHIFTR(test_nbr, 2);
printf("Shifting two positions right = %80X - %d\n", test_nbr, test_nbr);
}
#ifndef BITSHIFT_H
#define BITSHIFT_H
#define BIT_POS(N) ( 1U << (N) )
#define SET_FLAG(N, F) ( (N) |= (F) )
#define CLR_FLAG(N, F) ( (N) &= -(F) )
#define TST_FLAG(N, F) ( (N) & (F) )
#define BIT_RANGE(N, M) ( BIT_POS((M)+1 - (N))-1 << (N) )
#define BIT_SHIFTL(B, N) ( (unsigned)(B) << (N) )
#define BIT_SHIFTR(B, N) ( (unsigned)(B) >> (N) )
#define SET_MFLAG(N, F, V) ( CLR_FLAG(N, F), SET_FLAG(N, V) )
#define CLR_MFLAG(N, F) ( (N) &= ~(F) )
#define GET_MFLAG(N, F) ( (N) & (F) )
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment