Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Displaying an int as a formatted hex in an edit control

I was wondering if someone knew a better way to display a number in 16-bit hexadecimal format (e.g. 0x00FF) in an edit control. I'm starting with a UINT and using _itot_s() to get it into a string representing the number in hex. The problem is that I want to maintain the leading zeros, which the function throws out. I also want it to have the "0x" in front. My code to check the length of the string and add the zeros as necessary is below. I am relatively new at this, but my code seems unnecessarily bulky and awkward. Is there a better way?

[code]
UINT number;
int length;
TCHAR szTemp[5];
TCHAR szHex[7] = TEXT("0x");

_itot_s(number, szTemp, 5, 16);
length = _tcslen(szTemp);

if(length == 0)
{
szHex[2] = L'0';
szHex[3] = L'0';
szHex[4] = L'0';
szHex[5] = L'0';
szHex[6] = NULL;
}
if(length == 1)
{
szHex[2] = L'0';
szHex[3] = L'0';
szHex[4] = L'0';
szHex[5] = NULL;
}
if(length == 2)
{
szHex[2] = L'0';
szHex[3] = L'0';
szHex[4] = NULL;
}
if(length == 3)
{
szHex[2] = L'0';
szHex[3] = NULL;
}

_tcscat_s(szHex, 7, szTemp);

SetDlgItemText(hWnd, IDC_EDIT, szHex);
[/code]

I thought of a better way....

[code]
UINT number;
int length, i;
TCHAR szTemp[5];
TCHAR szHex[7] = TEXT("0x");

_itot_s(number, szTemp, 5, 16);

length = _tcslen(szTemp);

for(i=2;i<=5-length;i++)
szHex[i] = TEXT('0');

szHex[i] = NULL;

_tcscat_s(szHex, 7, szTemp);
SetDlgItemText(hWnd, IDC_EDIT, szHex);
[/code]

but I'm still wondering if there is a function to make this nicer.

Comments

  • Ed HallEd Hall Member Posts: 395
    Sorry I don't have the time to test this in a windows environment right now, but can't you just use sprintf to format your number the way you'd like and store it into a string for use in your display?

    [code]
    int i=56;
    char str[19];

    sprintf(str, "%0#18X", i);
    [/code]

    Take Care,
    Ed
Sign In or Register to comment.