Converting Decimal to Hexadecimal
Sometimes we need to convert a decimal value into a hexadecimal, usually when we're dealing with hardwares. I got the source from this website and modify it to work in C++ Builder environment. Well, I'm just a practical programmer so if things work smoothly and my program runs well without memory leaks I will be happy enough.
However, I also care about re-usability of my code, so I change the source code a little bit to make it easier to be used in the future:
AnsiString dec2hexConv(int dec)
{
int n;
int i;
int len = 0;
char str[20] = {0};
int temp_dec = dec;
while(temp_dec != 0)
{
temp_dec /= 16;
len++;
}
i = len - 1;
while(dec != 0)
{
n = dec % 16;
dec /= 16;
if(n < 10 )
{
str[i--] = n + '0';
}
else
{
str[i--] = (n - 10) + 'a';
}
}
str[len] = '\0';
return AnsiString(str);
}
Hope it is useful..
Labels: borland c++ builder, serial comm, work
0 Comments:
Post a Comment
<< Home