Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Language Examples - Converting Between Binary and Decimal

C Language Examples - Converting Between Binary and Decimal

C Language Examples C Language Examples

Convert between binary and decimal.

Example - Converting binary to decimal

#include

<

stdio.h

#include

<

math.h

int

convertBinaryToDecimal

(

long

long

n

)

;

int

main

(

)

{

long

long

n

;

printf

(

"

Enter a binary number:

"

)

;

scanf

(

"

%lld

"

, &

n

)

;

printf

(

"

Binary number %lld converted to decimal is %d

"

,

n

,

convertBinaryToDecimal

(

n

)

)

;

return

0

;

}

int

convertBinaryToDecimal

(

long

long

n

)

{

int

decimalNumber

=

0

,

i

=

0

,

remainder

;

while

(

n

!=

0

)

{

remainder

=

n

%

10

;

n

/=

10

;

decimalNumber

+=

remainder

pow

(

2

,

i

)

; ++

i

;

}

return

decimalNumber

;

}

The output is:



输入一个二进制数: 110110111

二进制数 110110111 转换为十进制为 439

Example - Converting decimal to binary

#include

<

stdio.h

#include

<

math.h

long

long

convertDecimalToBinary

(

int

n

)

;

int

main

(

)

{

int

n

;

printf

(

"

Enter a decimal number:

"

)

;

scanf

(

"

%d

"

, &

n

)

;

printf

(

"

Decimal number %d converted to binary is %lld

"

,

n

,

convertDecimalToBinary

(

n

)

)

;

return

0

;

}

long

long

convertDecimalToBinary

(

int

n

)

{

long

long

binaryNumber

=

0

;

int

remainder

,

i

=

1

,

step

=

1

;

while

(

n

!=

0

)

{

remainder

=

n

%

2

;

printf

(

"

Step %d: %d/2, remainder = %d, quotient = %d

\

n

"

,

step

++,

n

,

remainder

,

n

/

2

)

;

n

/=

2

;

binaryNumber

+=

remainder

i

;

i

*=

10

;

}

return

binaryNumber

;

}

The output is:



输入一个十进制数: 100

Step 1: 100/2, 余数 = 0, 商 = 50

Step 2: 50/2, 余数 = 0, 商 = 25

Step 3: 25/2, 余数 = 1, 商 = 12

Step 4: 12/2, 余数 = 0, 商 = 6

Step 5: 6/2, 余数 = 0, 商 = 3

Step 6: 3/2, 余数 = 1, 商 = 1

Step 7: 1/2, 余数 = 1, 商 = 0

十进制数 100 转换为二进制位 1100100

C Language Examples C Language Examples