Root Android Unique Serial Number


In Android devices how is the unique Serial number is assigned to each device? Most of the Samsung devices have a unique serial number on each device. When is this serial number is inserted? Is this serial number assigned before firmware installation or after installing the firmware? Or it has some mechanisim/ algorithm to assign the serial number during firmware is installed.

I want to burn firmware to devices but need some algorithm which helps me to assign the unique serial number to each device and it will remain same even if the firmware is burned multiple times.