> it should start convert function all over again
> and it never gets to cout<< hexChar[num%16] ... so why it works??
It would get to
cout<< hexChar[num%16]
when the called function returns.
See:
http://www.cprogramming.com/tutorial/lesson16.html
> if the negative hexadecimal numbers are the same as positives just with negetive sign infront of it
Typically, when a hexadecimal number is printed, each hex digit is a representation of the value of four bits. We make no distinction betwen a sign bit and other value bits. For instance, a 32-bit signed integer with one sign bit and 31 digit bits is treated as eight four-bit values. In other words, the signed int is treated as an unsigned int.
In printing out the hexadecimal literal,
hexChar[num%16]
is a technical error when
num
is a signed integer. It leads to undefined behaviour when num is negative. What would
-17%16
yield?
1 2 3 4 5 6 7 8 9 10
|
#include <iostream>
int main()
{
// what does this print out?
std::cout << std::hex << -17 << '\n' ;
// and what would this print out?
std::cout << (-17/10) << (-17%16) << '\n' ;
}
|
The simplest solution is to just make the function interpret the number as an unsigned value:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
#include <iostream>
void print_hex( unsigned int num ) ;
int main()
{
int num ;
while( std::cout << "number? " && std::cin >> num )
{
std::cout << "decimal: " << num << " hex: 0x" ;
if( num == 0 ) std::cout << '0' ;
print_hex(num) ;
std::cout << '\n' ;
}
}
void print_hex( unsigned int num )
{
static constexpr char digits[] = "0123456789abcdef" ;
if ( num != 0 )
{
print_hex( num/16 ) ;
std::cout << digits[ num%16 ] ;
}
}
|