Decimal to Hexadecimal Conversion in C# with Example Code

Decimal to Hexadecimal Conversion in C#

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.

Why Convert Decimal to Hexadecimal?

  • 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.

C# Example Code




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();
}
}
}

Key Points in Code:

  1. long.TryParse → Safely parses decimal values.

  2. Bitmask & 0xFFFFFF → Keeps only 24-bit value (common in RFID/Wiegand).

  3. ToString("X") → Converts to uppercase hexadecimal.

    • Example: 1234561E240

  4. Error Handling → If conversion fails, it stores an empty string.

Quick Conversion Example

long decimalValue = 305419896; // Example: 305419896 in decimal
string hexValue = decimalValue.ToString("X");
Console.WriteLine(hexValue); // Output: 12345678

✅ Output:

12345678

Conclusion

Converting decimal to hexadecimal in C# is very simple with .ToString("X").
If you are working with RFID cards, biometrics, or device protocols, applying a 24-bit mask before conversion ensures compatibility with most hardware formats.

This technique is not only useful for card numbers but also for low-level hardware data, memory addresses, and debugging binary protocols.

Post a Comment

0 Comments

Translate

Close Menu