# C and C++ bit Operations Tricks

This tip submitted by sedfy on 2013-10-02 05:40:17. It has been viewed 17678 times.
Rating of 4.2 with 69 votes

/*4-Get a bit value 0/1*/
#define Getbit(val,Bitno) (val&(1<
/*4-Set a bit value 1*/
#define setbit(val,Bitno) val|=(1<
/*1-set n bits starting from Sbit with length Blen in a char or byte to 1*/
#define GetNbitsB8(val,Sbit,Blen) (((0xff<>(8-Sbit-Blen)))&val)>>Sbit

/*1-set n bits in a word WD selected by a mask Msk (000011000 to set bits 3,4) to a certain value V01 to 0 or 1*/
#define setNbits(WD,Msk,V01) (WD & ~Msk)|((V01&0xFFFF)&Msk)

/*2-Get n bits starting from Sbit with length Blen for a 16bit word short/unsigned short */
#define GetNbitsW16(val,Sbit,Blen) (((0xffff<>(16-Sbit-Blen)))&val)>>Sbit

/*3-Get n bits starting from Sbit with length Blen for a 32bit word long/unsigned long/int*/
#define GetNbitsDW32(val,Sbit,Blen) (((0xffffffff<>(16-Sbit-Blen)))&val)>>Sbit

#define Unsetbit(val,Bitno) val&=~(1<#define GetLeftByte(word16) ((Ubyte8)(word16&0xFF00)>>8)
#define GetRightByte(word16) ((Ubyte8)(word16&0x00FF)>>8)
#define SetrightBit(word16,byte8) word16=((word16&0x00ff)|byte8)
#define SetLeftBit(word16,byte8) word16=((word16&0xff00)|(byte8<<8))

More tips