Dec2Bin, Bin2Dec Update

Email
 Submitted on: 7/31/2016 7:32:03 PM By: Ben128 Level: Beginner User Rating: Unrated Compatibility: Microsoft Visual C++ Views: 1978

Convert between decimal and binary update to the dec2bin to allow larger numbers than 255, Added Bin2Dec

code:
Can't Copy and Paste this?
 ``` //************************************** // Name: Dec2Bin, Bin2Dec Update // Description:Convert between decimal and binary update to the dec2bin to allow larger numbers than 255, Added Bin2Dec // By: Ben128 //************************************** /* 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. */ #include #include 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")); }```

Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

What do you think of this code (in the Beginner category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)

8/1/2016 12:30:39 PMThomas1965

The code has a small problem. In Dec2Bin memory gets allocated with malloc, but doesn't get deleted, so we have a memory leak.

(If this comment was disrespectful, please report it.)