Skip to content

Instantly share code, notes, and snippets.

@MitMaro
Created September 15, 2012 20:06
Show Gist options
  • Save MitMaro/3729535 to your computer and use it in GitHub Desktop.
Save MitMaro/3729535 to your computer and use it in GitHub Desktop.
cs3710a1q1
/*Question 1: Bitwise operators*/
#define INT_SIZE (sizeof(int) * 8)
#include <stdio.h>
/* Helper function to print a binary representation of an unsigned integer */
void print_int_as_binary_string(unsigned int b) {
int i;
char buffer[INT_SIZE + 1];
buffer[INT_SIZE] = '\0';
for (i = 31; i >= 0; i--) {
/* Adds 1 to the char '0' if bit is 1 to make the char a '1' */
buffer[i] = ((b >> ((INT_SIZE - 1) - i)) & 0x1) + '0';
}
printf("%s\n", buffer);
}
unsigned invert(unsigned int x, unsigned int p, unsigned int n){
int i;
for(i = p; i < p + n; i++){
x ^= (0x1 << INT_SIZE - i); /* XOR with a shifted bit mask */
}
return x;
}
int main (int argc, char *argv[]) {
int number = atoi(argv[1]);
int start = atoi(argv[2]);
int length = atoi(argv[3]);
// check for invalid input
if (start < 1 || length < 1 || start + length > INT_SIZE + 1) {
printf("Invalid start or length provided.\n");
return 0;
}
print_int_as_binary_string(number);
print_int_as_binary_string(invert(number, start, length));
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment