C++ Builder

La Isla Bonita



Binary Representation of Decimal Numbers
Binary Representation of Decimal Numbers


Description

This example shows how to convert a decimal number into a AnsiString that holds its binary representation.

For example the number 15 will be converted into the AnsiString: "00001111". The decimal number 1000 into "001111101000". The decimal number 1048576 into: "000100000000000000000000", etc.

This approach uses the IntToHex() function to convert decimal numbers (integers) to hexadecimal numbers and a std::map to convert hexadecimal numbers into strings (binary representation).

The two step conversion is done by the following function:

 String DecimalToBinaryStr(int DecimalNumber);
which takes a decimal number as a parameter and returns an AnsiString containing the binary representation of that number.

BinaryRepresentation.cpp

#include <vcl.h>
#pragma hdrstop

#include "BinaryRepresentation.h"
#include 
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;

//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------

String DecimalToBinaryStr(int DecimalNumber)
{
    std::map MapHex;

    MapHex["0" ] = "0000";
    MapHex["1" ] = "0001";
    MapHex["2" ] = "0010";
    MapHex["3" ] = "0011";
    MapHex["4" ] = "0100";
    MapHex["5" ] = "0101";
    MapHex["6" ] = "0110";
    MapHex["7" ] = "0111";
    MapHex["8" ] = "1000";
    MapHex["9" ] = "1001";
    MapHex["A" ] = "1010";
    MapHex["B" ] = "1011";
    MapHex["C" ] = "1100";
    MapHex["D" ] = "1101";
    MapHex["E" ] = "1110";
    MapHex["F" ] = "1111";

    // Set the minimum number of Hexadecimal digits to 2
    //
    String SBinary, SHex = IntToHex( DecimalNumber, 2);
    
    for (int i =1 ; i <= SHex.Length(); ++i)
        SBinary += MapHex[SHex[i]];
        
    return SBinary;
}

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    int DecimalNumber = 1048576;
    String SBinary = DecimalToBinaryStr(DecimalNumber);    
}

Homepage

Copyright © 1997-2002 Rodolfo A. Frino. All rights reserved.