Skip to content

Instantly share code, notes, and snippets.

@afroewis
Last active November 8, 2021 14:05
Show Gist options
  • Save afroewis/15290027d2d9be70901d6757ef01c612 to your computer and use it in GitHub Desktop.
Save afroewis/15290027d2d9be70901d6757ef01c612 to your computer and use it in GitHub Desktop.
C#: DateTime to BCD (Binary Coded Decimal)
public static byte[] FromDateTime(DateTime dateTime)
{
var daysFirstByte = dateTime.Day / 10;
var daysSecondByte = dateTime.Day - daysFirstByte * 10;
byte daysBcd = (byte)((daysFirstByte << 4) | daysSecondByte);
var monthsBcdFirstByte = dateTime.Month / 10;
var monthsBcdSecondByte = dateTime.Month - monthsBcdFirstByte * 10;
byte monthsBcd = (byte)((monthsBcdFirstByte << 4) | monthsBcdSecondByte);
var year = dateTime.Year - 2000;
var yearBcdFirstByte = year / 10;
var yearBcdSecondByte = year - yearBcdFirstByte * 10;
byte yearsBcd = (byte)((yearBcdFirstByte << 4) | yearBcdSecondByte);
return new[] {daysBcd, monthsBcd, yearsBcd};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment