Created
July 31, 2016 19:35
-
-
Save DreamVB/c7bc2cbd490cd30a4fd0c0c6dde4e752 to your computer and use it in GitHub Desktop.
Decimal To Binary, Binary To Decimal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| Decimal To Binary, Binary To Decimal By DreamVB | |
| Version 1.0 | |
| Two functions to convert between decimal and binary | |
| Please feel free to use as you like. | |
| Feel free to update or fix an errors. | |
| */ | |
| #include <stdio.h> | |
| #include <string> | |
| char *Dec2Bin(int dec){ | |
| char TempBin[32]; | |
| int j = 0; | |
| int i = 30; | |
| int t = dec; | |
| int bitcnt = 0; | |
| //Get the number of bits that make up the number. | |
| while(t > 0){ | |
| //Keep divideing by 2 | |
| t/=2; | |
| //INC bit counter | |
| bitcnt++; | |
| } | |
| //Minus 1 | |
| bitcnt--; | |
| while(i >=0) | |
| { | |
| //Build the binary number. | |
| if((dec & (1 << i)) != 0){ | |
| TempBin[j] = '1'; | |
| }else{ | |
| TempBin[j] = '0'; | |
| } | |
| //INC Counters | |
| i--; | |
| j++; | |
| } | |
| //Reserve array contents | |
| for(i=bitcnt;i>=0;i--){ | |
| //Reserve array chars | |
| TempBin[bitcnt-i] = TempBin[30-i]; | |
| } | |
| //Convert char array to Char* | |
| i = strlen(TempBin); | |
| //Resize array to hold the data | |
| char *pBin =(char*)malloc(i+1*sizeof(char)); | |
| //Copy from TempBin to pStr | |
| strcpy(pBin,TempBin); | |
| //Set ending | |
| pBin[bitcnt+1] = '\0'; | |
| //Return | |
| return pBin; | |
| } | |
| int Bin2Dec(char*Bin){ | |
| int dec = 0; | |
| int n = 0; | |
| //Convert binary number to decimal number | |
| for(int i=strlen(Bin)-1;i>-1;i--){ | |
| //Check if bit is set | |
| if(Bin[i] == '1'){ | |
| //Make decimal number | |
| dec+=pow(2,n); | |
| } | |
| //INC Counter | |
| n+=1; | |
| } | |
| //Return | |
| return dec; | |
| } | |
| void main(){ | |
| printf("Decimal 518 to binary is %s\n",Dec2Bin(512)); | |
| printf("Binary 1111110111011000 to decimal is %d\n",Bin2Dec("1111110111011000")); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment