Working with RFID cards, hardware devices, or low-level protocols often requires converting decimal values into hexadecimal format. In C#, this is quite straightforward using the built-in formatting options.
Let’s break it down with a practical example.
Hexadecimal (base 16) is commonly used in embedded systems, RFID/Wiegand formats, and hardware communication.
For example, RFID card numbers are stored in decimal format but devices may expect them in hexadecimal (24-bit masked) representation.
Here’s a working method that fetches user data from SQLite and converts the Card column from decimal to hexadecimal:
public static DataTable SelectAllUserData(){ DataTable dt = null; SQLiteConnection con = null; try { string query = @"SELECT DGD.[Index], DGD.MachineNo, DGD.DeviceType, DGD.UserId, UserName, pwd, [Card], InputNo, Template, Privilege, IsEnabled FROM tblDemographicsData DGD LEFT OUTER JOIN tblBiometircsData BMD ON DGD.UserId = BMD.UserID ORDER BY CAST(DGD.UserId AS INTEGER), InputNo ASC"; con = new SQLiteConnection(strCon); con.Open(); SQLiteCommand cmd = new SQLiteCommand(query, con); SQLiteDataAdapter sda = new SQLiteDataAdapter(cmd); dt = new DataTable(); sda.Fill(dt); // Convert decimal "Card" values into Hexadecimal foreach (DataRow row in dt.Rows) { if (row["Card"] != DBNull.Value) { string cardValue = row["Card"].ToString(); if (long.TryParse(cardValue, out long dec)) { // Keep only lower 24 bits (for RFID/Wiegand format) long masked = dec & 0xFFFFFF; // Convert to Hexadecimal (uppercase) row["Card"] = masked.ToString("X"); } else { row["Card"] = string.Empty; } } } return dt; } finally { if (con != null) { con.Close(); con.Dispose(); } }}
long.TryParse → Safely parses decimal values.
Bitmask & 0xFFFFFF → Keeps only 24-bit value (common in RFID/Wiegand).
ToString("X") → Converts to uppercase hexadecimal.
Example: 123456 → 1E240
Error Handling → If conversion fails, it stores an empty string.
long decimalValue = 305419896; // Example: 305419896 in decimalstring hexValue = decimalValue.ToString("X");Console.WriteLine(hexValue); // Output: 12345678
✅ Output:
12345678
.ToString("X").This technique is not only useful for card numbers but also for low-level hardware data, memory addresses, and debugging binary protocols.
0 Comments
Thanks for Commenting on our blogs, we will revert back with answer of your query.
EmojiThanks & Regards
Sonu Yadav