文档库 最新最全的文档下载
当前位置:文档库 › 十进制与二进制转换源代码

十进制与二进制转换源代码

/*Convert a binary number t oa decimal number.
Written by :
Date :
*/
#define _CRT_SECURE_NO_WARNINGS

#include
#include

//Function Declaration

long getNum(void);
long binaryToDcimal(long binary);
long powerTwo(long num);
long firstDigit(long num);
bool validateBinary(long binary);

int main(void)

{
//Local Declaration
long binary;
long decimal;

//Statements
binary = getNum();
decimal = binaryToDcimal(binary);
printf("The binary number was:%d", binary);
printf("\nThe decimal number is :%d\n", decimal);
system("pause");
return 0;

}//main

/*===========================getNum==========================
This function reads and validates a binary number
from the keyboard.
Pre nothing
Post a valid binary number is returned
*/

long getNum(void)
{
//Local declaration
bool isValid;
long binary;
//Statements
do
{
printf("Enter a binary number (zeros and ones):");
scanf("%d", &binary);
isValid = validateBinary(binary);
if (!isValid)

printf("\a\aNot binary .Zeros/ones only\n\n");
}


while (!isValid);
return binary;


}//getNum

/*===========================binaryToDcimal========================================
change a binary number to a decimal number.
Pre binary is a number containing only 0 or 1
Post returns decimal number
*/
//Local Declaraetions
long binaryToDcimal(long binary)
{

//Local Declarations
long decimal;

//Statements
decimal = 0;
for (int i = 0; binary != 0; i++)
{
decimal += firstDigit(binary) * powerTwo(i);
binary /= 10;
}//for i
return decimal;

}//binaryToDecimal

/*====================================validateBimary=================================================
check the digits in a binary number for only 0 and 1
Pre binary is a number to be validated
post return true is valid;false if not
*/
bool validateBinary(long binary)
{
//Statements
while (binary != 0)
{

if (!(binary & 10 == 0 || binary % 10 == 1))
return false;

binary /= 10;
}//while
return true;

}//validateBinary

/*===================================powerTwo===========================================================
This function raises 2 to the power num
Pre number is exponent
Post Returns 2 to power of num
*/

long powerTwo(long num)
{
//Local Declarations
long power = 1;

//Statements
for (int i = 1; i <= num; i++)
power *= 2;
return power;
} //powerTwo

/*===============================firstDigit=============================================================
This function returns the right most digit of num
Pre the integer num
post the right digit of num returned

*/
long firstDigit(long num)
{
//Statements
return (num % 10);

}//firrsDigit

相关文档
相关文档 最新文档