Base representation
name | form |
---|---|
Binary | 0b+content/ 0B+content |
Octal | 0+Content |
Decimal | content |
Hexadecimal | 0x+content/ 0x+content |
The following is the test procedure:
#include <iostream>
using namespace std;
int main()
{
int a = 20;
int b = 024;
int c = 0x14;
int d = 0X14;
int e = 0b10100;
int f = 0B10100;
int b2 = 0024;
int c2 = 0x014;
// int c3 = 00x14; //This is an error.
int e2 = 0b010100;
cout << a << " " << b << " " << c << " " << d << " " << e <<
" " << f << " " << b2 << " " << c2 << " " << e2 << endl;
return 0;
}
Result:
20 20 20 20 20 20 20 20 20
Base conversion
The following defines the binary-to-decimal conversion function in Header File Binary.h :
1. binary_to_decimal() : binary→decimal
2. decimal_to_binary() : decimal→binary
#ifndef BINARY_H
#define BINARY_H
#include <cmath>
int binary_to_decimal(unsigned long bin1)
{
unsigned long dec1 = 0;
unsigned long tem1 = bin1;
unsigned i = 0;
while (tem1 != 0)
{
dec1 += pow(2, i++) * (tem1 % 10);
tem1 /= 10;
}
return(dec1);
}
int decimal_to_binary(unsigned long dec2)
{
unsigned long bin2 = 0;
unsigned long tem2 = dec2;
unsigned j = 0;
while (tem2 != 0)
{
bin2 += pow(10, j++) * (tem2 % 2);
tem2 /= 2;
}
return(bin2);
}
#endif // !BINARY_H
The use example is in [C++ Primer(5th Edition) Exercise] Exercise Program-Chapter4 Exercise Section 4.8(ie Exercise 4.25-27).
Also note that the power is not ^!!! , this symbol is explained in the English version P154.
Of course, you can write other hexadecimal conversion programs by analogy.
See also
Teddy van Jerry's navigation page
【C++ Primer(5th Edition) Exercise】exercise program-Chapter2 (Chapter 2)