Run Code

API

Code Wall

Users

Misc

Feedback

Login

Theme

Privacy

Patreon
Jan23
/*Simple program showing how to read an integer and printing it to output in different formats.*/ #include "stdio.h" //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 31i binary[31i] = 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: %x\n", a); char binary[33]; DecimalToBinary(a, binary); printf ("Binary: %s\n", binary); // reset the LSB to 0 and leave the rest of the bits unchanged int temp; //0xfffe in this operation is called mask //temp = a & 0xfffffffe; //printf("Hex: %x\n", a); //DecimalToBinary(temp, binary); //printf("Binary: %sn", binary); //&& is logical operation that is true false //print the result in hex and binary //now set MSD to 1 and leave the rest of the bits unchanged //1000=8 temp = a  0x80000000; //or statement to change MSD to one, integer is 32 bits printf("Hex: %x\n", temp); DecimalToBinary(temp, binary); printf("Binary: %sn", binary); return 0; }
run

edit

history

help
0
Please
log in
to post a comment.
Spring 2017 Project 2 v.02
A_141128_MatricesSuma
NETFLIX TERMINADO
14th Feb Programming Project v.01
stringify
Array non repeated alphabets
null p null q
C_141127_Matriz01
Lab 9 v0.9
No warnings!!!
Please log in to post a comment.