I am working on the Firmware for an embedded USB project. The production programmer I would like to use automatically writes the Serial Number into the device flash memory at a specified memory address. The programmer stores the serial number as Hex digits in a specified number of bytes. For example, if I tell it to store the serial number 123456 at address 0x3C00 my memory looks like this:
0x3C00 - 00
0x3C01 - 01
0x3C02 - E2
0x3C03 - 40
//(123456 in Hex = 1E240)
The problem is, when my host application reads the serial number from the device it is looking for a unicode char array. So my serial number should be ...
{ '1','0',
'2','0',
'3','0',
'4','0',
'5','0',
'6','0'}
When the
So in my firmware, which I'm writing in C, is it possible to retrieve the hex serial number from flash, encode it into a unicode char array and store it in a variable in Ram?
If the serial number fits into 32 bits and the platform is big endian and supports Unicode, 32 bit ints and the standard C libraries then this is pretty straightforward as other answers have shown. If the platform has 32 bit ints and 8 bit chars but is little endian and/or doesn't support Unicode, and if the serial number can vary in length, then the below may be useful, though it's a little workmanlike.
void extract_serial_number(unsigned char* address, unsigned int bytes, char* buffer) {
unsigned int value = 0;
char c, *start = buffer;
while (bytes--) { /* read the serial number into an integer */
value = value << 8;
value |= *address++;
}
while (value > 0) { /* convert to 16 bit Unicode (reversed) */
*buffer++ = '0' + value % 10;
*buffer++ = '\0';
value /= 10;
}
*buffer++ = '\0';
*buffer++ = '\0';
buffer -= 4;
while (buffer > start) { /* reverse the string */
c = *buffer;
*buffer = *start;
*start = c;
buffer -= 2;
start += 2;
}
}