Home Articles Books Downloads FAQs Tips

Q: Display an integer in HEX or binary format


Answer

The VCL contains a global function called IntToHex that takes an integer and creates an AnsiString that contains the hex representation of the number. IntToHex is located in SYSUTILS.PAS. It takes two arguments: the first is the number that you want to display in HEX format, and the second argument determines how many digits you want to display. Here is an example:

int nValue = 378;
Label1->Caption = IntToHex(nValue,8);

You can also use the itoa function from the C RTL. itoa allows you to specify a radix argument. Use a radix of 16 to convert the number to HEX format. itoa has the extra benefit that it can convert the number to binary format.

int nValue = 452;
char buf[40];
itoa(nValue, buf, 2);  // 2 means binary, 16 would be hex
Label1->Caption = buf;

Of course, you could also use streams, the RTL sprintf function, or the sprintf member function of AnsiString (new in BCB4).

// using streams to display a number in hex.
#include <sstream>
using namespace std;
...
...
int nValue = 452;
ostringstream ostr;
ostr << hex << nValue;
Label1->Caption = ostr.str().c_str();

// using sprintf to display a number in hex.
int nValue = 452;
char buf[40];
sprintf(buf, "%08X", nValue);
Label1->Caption = buf;

// using AnsiString::sprintf to display a number in hex.
int nValue = 452;
AnsiString str;
str.sprintf("%08X", nValue);
Label1->Caption = str;


Copyright © 1997-2000 by Harold Howe.
All rights reserved.