Write a C program to toggle odd bits(8 bit manipulation).
#include <stdio.h>
int main() {
int i, value, temp = 1;
/* Get the 8 bit input value from user */
printf("Enter your input value(0-255):");
scanf("%d", &value);
if (value < 0 || value > 255) {
printf("Threshold Value Exceeded!!\n");
return 0;
}
/* Set the odd bits alone in 8 bit data - 0101 0101 */
for (i = 0; i <= 7; i = i + 2) {
temp = temp | (1 << i);
}
/* XOR value with 0101 0101 toggles odd bits */
value = (value ^ temp);
/* print the result */
printf("Result: %d\n", value);
return 0;
}
Example: Input data is 179
Step 1: Find binary Equivalent of 179
Binary equivalent of 179 is 1011 0011.
Step 2: Find a 8 bit value whose odd bits are 1. 0101 0101 has 1 in the odd bits.
0101 0101 is the binary equivalent of 85
Step 3: XOR 179 with 85 to toggles odd bits of the given input data.
Output is 230(11100110)
Step 1: Find binary Equivalent of 179
Binary equivalent of 179 is 1011 0011.
Step 2: Find a 8 bit value whose odd bits are 1. 0101 0101 has 1 in the odd bits.
0101 0101 is the binary equivalent of 85
Step 3: XOR 179 with 85 to toggles odd bits of the given input data.
Output is 230(11100110)
int main() {
int i, value, temp = 1;
/* Get the 8 bit input value from user */
printf("Enter your input value(0-255):");
scanf("%d", &value);
if (value < 0 || value > 255) {
printf("Threshold Value Exceeded!!\n");
return 0;
}
/* Set the odd bits alone in 8 bit data - 0101 0101 */
for (i = 0; i <= 7; i = i + 2) {
temp = temp | (1 << i);
}
/* XOR value with 0101 0101 toggles odd bits */
value = (value ^ temp);
/* print the result */
printf("Result: %d\n", value);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your input value(0-255):179
Result: 230
Enter your input value(0-255):179
Result: 230
No comments:
Post a Comment