1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
|
#include <stdio.h>
#define TAKE 5
// now a function
int stripNybble(int x, int carac) {
int sum=0,i=0;// sum zeroed
int masca=0xf;// was 0xff
int aux=0;// for completeness
#if TAKE == 1
while(i<8){
aux = x & masca;
if(aux==carac){
sum=sum+0;
masca=masca<<4;
}else{
sum=sum+aux;
masca=masca<<4;
}
i++;
}
#elif TAKE == 2
while(i<8){
aux = x & masca;
if(aux==carac){
//sum=sum+0; // TAKE 2
//masca=masca<<4; // TAKE 2
}else{
sum=sum+aux;
//masca=masca<<4; // TAKE 2
}
masca=masca<<4; // TAKE 2
i++;
}
#elif TAKE == 3
while(i<8){
aux = x & masca;
if(aux==carac){
//sum=sum+0; // TAKE 2
//masca=masca<<4; // TAKE 2
}else{
sum=sum+aux;
//masca=masca<<4; // TAKE 2
}
carac=carac<<4; // TAKE 3 - also shift carac
masca=masca<<4; // TAKE 2
i++;
}
#elif TAKE == 4
// exploit fact that if you shift a value left (or right) enough times
// it eventually becomes 0 to eliminate the need for i
while(0 != masca){
aux = x & masca;
if(aux != carac){
sum=sum|aux; // and use bit-wise or rather than add
}
carac=carac<<4;
masca=masca<<4;
}
#elif TAKE == 5
while(0 != masca){
aux = x & masca;
if(aux != carac){
sum |= aux; // switch to short form of sum = sum | aux, etc
}
carac <<= 4;
masca <<= 4;
}
#endif
return sum;
}
int main(){
struct TestCase {
int x;
int carac;
int expectedResult;
};
//easier to define test cases in hex
TestCase testCases[] =
{ {0x64C6, 0x6, 0x04C0}
, {0x1234, 0x1, 0x0234}
, {0x1234, 0x4, 0x1230}
, {0x3535, 0x3, 0x0505}
, {0x3535, 0x5, 0x3030}
, {0x6666, 0x6, 0x0000}
, {0x6666, 0x2, 0x6666} };
const int count = sizeof(testCases)/sizeof(testCases[0]);
int passes = 0;
for(int i = 0; i < count; ++i) {
printf("INPUT\n");
printf("in dec : %d\n", testCases[i].x);
printf("in hex : %x\n", testCases[i].x);
printf("REMOVE all nybbles which are %x\n", testCases[i].carac);
int result = stripNybble(testCases[i].x, testCases[i].carac);
printf("OUTPUT\n");
printf("in dec : %d\n", result);
printf("in hex : %x\n", result);
if(result == testCases[i].expectedResult)
{
printf("pass!\n");
++passes;
}
else
{
printf("fail!\n");
}
printf("\n");
}
printf("RESULTS\n");
printf("ran %d\n", count);
printf("passed %d\n", passes);
printf("failed %d\n", (count- passes));
printf("\n");
return 0;
}
|