It is unclear how you are intending to represent this uint32_t
, but your code fragment suggest that you are expecting hexadecimal (or perhaps BCD). In that case:
for( int shiftby = 28; shiftby >= 0 ; shiftby -= 4 )
{
char hexdigit = (seconds >> shiftby) & 0xF ;
buf[position++] = hexdigit < 10 ? hexdigit + '0' : hexdigit + 'A' - 10 ;
}
Note that the only real difference between this and your code is the conversion to hex-digit characters by adding conditionally either '0'
or 'A' - 10
. The use of shiftby
as the loop control variable is just a simplification or your algorithm.
The issue with your code is that it inserted integer values 0 to 15 into buf
and the characters associated with these values are all ASCII control characters, nominally non-printing. How or whether they render as a glyph on any particular display depends on what you are using to present them. In Windows console for example, printing characters 0 to 15 results in the following:
00 = <no glyph>
01 = '☺'
02 = '☻'
03 = '♥'
04 = '♦'
05 = '♣'
06 = '♠'
07 = <bell> (emits a sound, no glyph)
08 = <backspace>
09 = <tab>
10 = <linefeed>
11 = '♂'
12 = '♀'
13 = <carriage return>
14 = '♫'
15 = '☼'
The change above transforms the values 0 to 15 to ASCII '0'
-'9'
or 'A'
-'F'
.
If a hexadecimal presentation is not what you were intending then you need to clarify the question.
Note that if the encoding is BCD (Binary Coded Decimal) where each decimal digit is coded into a 4 bit nibble, then the conversion can be simplified because the range of values is reduced to 0 to 9:
char bcddigit = (seconds >> shiftby) & 0xF ;
buf[position++] = bcddigit + '0' ;
but the hex conversion will work for BCD also.