I'd be obliged if someone could validate the functions I've written below from the try-it-yourself excercises of K&R:
Code:#include <stdio.h> #include <stdlib.h> #include <string.h> void DWordToWords(const int DWord, short int* LoWord, short int* HiWord); void MakeDWord(const short LoWord, const short HiWord, int* DWord); unsigned GetBits(unsigned, int, int); unsigned SetBits(unsigned, int, int, int); unsigned Invert(unsigned, int, int); /*int main(void) { int DWord; short LoWord, HiWord; DWord = 1066825727; LoWord = HiWord = 0; DWordToWords(DWord, &LoWord, &HiWord); printf("DWord = %d\nLoWord = %d\nHiWord = %d\n\n", DWord, LoWord, HiWord); DWord = 0; MakeDWord(LoWord, HiWord, &DWord); printf("DWord = %d\nLoWord = %d\nHiWord = %d\n\n", DWord, LoWord, HiWord); }*/ void DWordToWords(const int DWord, short int* LoWord, short int* HiWord) { *LoWord = DWord & ~(~0<<16); *HiWord = DWord>>16; } void MakeDWord(const short LoWord, const short HiWord, int* DWord) { *DWord = HiWord<<16; *DWord |= LoWord; } unsigned int GetBits(unsigned x, int p, int n) { /*gets the right-adjusted n bits of integer x starting from position p*/ return (x>>(p-n+1)) & ~(~0<<(p-n)); } unsigned int SetBits(unsigned x, int p, int n, int y) { /*set n bits of integer x starting from position p to the right-most n bits in integer y*/ y&=~(~0<<n); return x|((y&~(~0<<n))<<(p-n+1)); } unsigned Invert(unsigned x, int p, int n) { /*Inverts n bits in x starting from position p*/ int temp=GetBits(x, p, n); temp=~temp; return SetBits(x, p, n, temp); }




Reply With Quote