Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Bitwise Operations
/*Simple program showing how to read an integer and printing it to output in different formats.*/ #include "stdio.h" // 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; int temp; 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); //write a few lines of code that gives the lowest significant byte (8 bits) as an int or char //a=0xabcd1234 output = 0x34 //if a=-1=ffffffff output=0xff temp = a % 256; //2^(number of bits you want out) %2 gives 1 bit, %4 for 2 bits, %8 for 3 and so on printf ("Hex: 0x%x\n", temp); //give four bits starting from bit position 3 //temp = a >> 3; //right shift 3 times //temp = temp & 0xf; //this is called masking, all unwanted bits become 0 and wanted bits stay the same temp = ( a >> 3) && 0xf; //top two lines into one printf("Hex: 0x%x\n", temp); //& operation can be used to force some bits to 0 //the mask you need has 0 on those bits and 1 on the rest //sets the bits 4, 5 and 6 to 1 and leave the rest of the bits unchanged temp = a | 0x70; //another kind of mask with or gate to force a 1 printf ("Hex: 0x%x\n", temp); DecimalToBinary(temp, binary); printf("Binary: %s\n", binary); return 0; }
run
|
edit
|
history
|
help
0
Address.c
FunPointBreakfast
Project 4 v1.1
C_141203_CTYPE
Prime no in given array
string_ptr_to_fct_param
1.8 Parallizing for loop
use_of_bool_in_loop
1.9 Time Function
Iterated sums