#include <iostream>
using namespace std;
void setBits(int& number, char ch, int pos){
for(int i = pos, j = 1; i < pos + 8; (ch&(1<<(j-1))) ? number |= 1 << i - 1 : number &= ~(1 << (i-1)), i++, j++);
}
int main(){
int value1 = 16384; // 100000000000000
int value2 = 32767; // 111111111111111
int value3 = 16511; // 100000001111111
char a = 0xFF; // 11111111
char b = 0xAA; // 10101010
char c = 0x83; // 10000011
setBits(value1, a, 3);
cout << value1 << endl; // 100001111111100, 17404
setBits(value2, b, 1);
cout << value2 << endl; // 111111110101010, 32682
setBits(value3, c, 3);
cout << value3 << endl; // 100001000001111, 16911
return 0;
}
Friday, 22 November 2013
Set Bits Function
Another challenge was given by Fardad today. We have to create a function to set the bits of an integer using the bit pattern of a character and a given position. Here it is:
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment