Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
bitwise manipulation
// write a function that gets an integer and a mask and returns the result of using the mask to reset some bits to 0 int ResetBits(int a, int mask) { return (a & mask); } //converts decimal value to a string that represents the binary number //note that decimal is already represented in binary in the memory //all we need is an array of characters 0 and 1 that show the number in binary int DecimalToBinary(int decimal, char *binary) { unsigned int temp = decimal; int i; for (i=0; i<32; i++) { //ASCII code for '0' is 48 and for '1' is 49 //the bit we calculate in this loop is Least Significant Bit (LSB), so the index is 31-i binary[31-i] = 48+ temp % 2; //dividing by 2, simply shifts the number to right and allows us to process the next bit temp = temp / 2; } //an end is put at the end of binary string. Again this is not a number, but an array of '0's and '1's binary [32] = 0; } int main(void) { int a; printf("Please input an integer value: "); scanf("%d", &a); printf("\nDecimal: %d\n", a); printf("Hex: 0x%x\n", a); char binary[33]; DecimalToBinary(a, binary); printf ("Binary: %s\n", binary); // reset the LSB to 0 andleave the rest of the bits unchaged // print the result in hex and binary int tem1; tem1 = (a & 0x00000050); printf("Hex: 0x%x\n", tem1); DecimalToBinary(tem1, binary); printf ("Binary: %s\n", binary); if (tem1-0x00000010 != 0) { printf ("False\n"); } else{printf ("True\n");} int temp; //oxfffe in this operation is called mask temp = ResetBits(a, 0xffffff4f); printf("Hex: 0x%x\n", temp); DecimalToBinary(temp, binary); printf ("Binary: %s\n", binary); // reset the MSB to 1 andleave the rest of the bits unchaged // print the result in hex and binary // 1000 = 8 in hexadeciaml int tem; tem = (a | 0x0000000F); printf("Hex: 0x%x\n", tem); DecimalToBinary(tem, binary); printf ("Binary: %s\n", binary); return 0; }
run
|
edit
|
history
|
help
0
prime numbers using functions
120465-11.1-3E
2.2 Comparision with Matrix Addition Execution Time
lab 12 v1
B_141125_Burbuja
Collatz(3k+1)
test
eliminate_duplicates.c
Project 3 Part 1 v2
xd