问题
In a part of a software, card is read by a card reader and is allocated to an user. And in other part of this software, in a terminal by same card reader, the user card is read and fetch data from database by card serial number and etc.
In a new part of this software, there are a new terminal with a new card reader. card is read from this card reader and fetch data from database and etc.
So, now the problem is that a same card that is read by this two card readers are different in type. The first device return card id as a hexadecimal string, like this:
2E 6F 27 3F
This hexadecimal string is converted to decimal and is stored in the database. For example, the above hexadecimal string is converted to this integer:
779036479
Now, when second card reader read this same card, the card id is an array of bytes, like this for that card:
byte0: 49
byte1: 48
byte2: 53
byte3: 57
byte4: 53
byte5: 52
byte6: 56
byte7: 57
byte8: 55
byte9: 52
How can I coordinate this two serial number of same card with each other? In other words, I want to convert this array of bytes to corresponding hex code, so that this hex code is the serial number of that card that first device is return?
The card is Mifare.
回答1:
The answer is that the second reader is returning ASCII encoded decimals. Your number is 1059548974
. This number, encoded into hexadecimals is 3F276F2E
if you use Big Endian encoding. If you use Little Endian encoding then you will get 2E6F273F
which should be familiar to you.
So:
- decode the returned byte array to ASCII, retrieving the string
"1059548974"
- convert that string to an integer using
Convert.ToUInt32(str);
- reverse the bytes in the integer
Probably the best way to reverse the bytes is this piece of code:
public static UInt32 ReverseBytes(UInt32 value)
{
return (value & 0x000000FFU) << 24 | (value & 0x0000FF00U) << 8 |
(value & 0x00FF0000U) >> 8 | (value & 0xFF000000U) >> 24;
}
回答2:
Its rather hard to understand just exactly what your wanting, but in the bottom you state: 'in other words, i want to convert this array of bytes to corresponding hex code'.
You can perform that operation like so:
public static string ByteArrayToString(byte[] ba)
{
StringBuilder sb = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
{
sb.AppendFormat("{0:x2}", b);
}
return sb.ToString();
}
Just pass in your Byte array and the result will be your hex conversion in string format.
Edit: This will probably yield the same results, but try this:
byte[ ] bytes = {0, 1, 2, 4, 8, 16, 32, 64, 128, 255 }
Console.WriteLine( BitConverter.ToString( bytes ) );
来源:https://stackoverflow.com/questions/17174621/coordinate-id-of-same-card-that-is-read-by-two-different-card-readers