Delphi Extended to C# - c#

how to convert a floating point 10 byte Hex string (Extended datatype in Delphi) to a C# datatype?
For example:
00 00 00 00 00 00 00 80 ff 3f is at Delphi 1

Was involved in same issue, sharing my solution somebody can find useful:
var extendedSize = 10;
var buf = new byte[extendedSize];
// Populate buffer with something like: { 0x00, 0x68, 0x66, 0x66, 0x66, 0x66, 0x66, 0xA2, 0x02, 0x40 } = 10.15
// Read(buf, extendedSize);
var sign = (buf[extendedSize - 1] & 0x80) == 0x80 ? -1 : 1;
buf[extendedSize - 1] = (byte)(buf[extendedSize - 1] & 0x7F);
var exp = BitConverter.ToUInt16(buf, extendedSize - 2);
var integral = (buf[extendedSize - 3] & 0x80) == 0x80 ? 1 : 0;
// Calculate mantissa
var mantissa = 0.0;
var value = 1.0;
var fractal = BitConverter.ToUInt64(buf, 0);
while (fractal != 0)
{
value = value / 2;
if ((fractal & 0x4000000000000000) == 0x4000000000000000) // Latest bit is sign, just skip it
{
mantissa += value;
}
fractal <<= 1;
}
return sign * (Math.Pow(2, exp - 16383)) * (integral + mantissa);
Code needs to be improved with NaN and Inf checks and probably "double" needs to be replaced by "decimal".

Ok, here is my solution:
Every string contains a factor byte at the second position. In my example the factor is ff.
Now I have to convert the string via Floating-Point Conversion to decimal and multiply with the factor byte to get the result.
Example:
3f ff 80 00 00 (32bit) -> remove the factor byte (ff) -> 3f 80 00 00 -> convert to decimal -> result: 1 -> multiply with factor -> 1 * 1 -> result: 1
I hope this was helpfully

Related

How to Parse received Hex bytes into readable string

As the title says, I've been working on MiFare Classic reading a card.
I'm using the MiFare v1.1.3 Library from NuGet
and it returns a byte array, which I parse to readable Hex strings, by looping thru it.
Here's the code snippet:
int sector = 1;
int block = 0;
int size = 16;
var data = await localCard.GetData(sector, block, size);
string hexString = "";
for (int i = 0; i < data.Length; i++)
{
hexString += data[i].ToString("X2") + " ";
}
// hexString returns 84 3D 17 B0 1E 08 04 00 02 63 B5 F6 B9 BE 77 1D
Now, how can I parse it properly?
I've tried parsing it into ASCII, ANSI, Int, Int64, Base64, Long
and all of them didn't match the 'data' that it's suppose to contain
EDIT:
The expected output: 1206058
HEX String returned: 84 3D 17 B0 1E 08 04 00 02 63 B5 F6 B9 BE 77 1D
I've checked the source code
it looks like both Task<byte[]> GetData Task SetData methods do not have any special logic to transform the data. Data are just saved (and read) as byte[]
I suppose that you have to contact author/company that has wrote data you are trying to read.
The expected output: 1206058
Looks strange since you are reading 16 bytes size = 16 and expecting 7 characters to be read.
Is it possible that block or sector values are incorrect ?
I have written a simple program to solve your problem. Perhaps this is what you want to achieve:
// The original byte data array; some random data
byte[] data = { 0, 1, 2, 3, 4, 85, 128, 255 };
// Byte data -> Hex string
StringBuilder hexString = new StringBuilder();
foreach (byte item in data)
{
hexString.Append($"{item.ToString("X2")} ");
}
Console.WriteLine(hexString.ToString().Trim());
// Hex string -> List of bytes
string[] hexArray = hexString.ToString().Trim().Split(' ');
List<byte> dataList = new List<byte>();
foreach (string item in hexArray)
{
dataList.Add(byte.Parse(item, System.Globalization.NumberStyles.HexNumber));
}
dataList.ForEach(b => Console.Write($"{b} "));
Console.WriteLine();
If it is not the right solution please provide us more info about your problem.
If var data potentially is string - you can reverse it from hex by:
// To Hex
byte[] plainBytes = Encoding.ASCII.GetBytes("MiFare v1.1.3");
string hexString = "";
for (int i = 0; i < plainBytes.Length; i++)
hexString += plainBytes[i].ToString("X2") + " ";
Console.WriteLine(hexString); // Result: "4D 69 46 61 72 65 20 76 31 2E 31 2E 33"
// From Hex
hexString = hexString.Replace(" ", ""); // Remove whitespaces to have "4D69466172652076312E312E33"
byte[] hexBytes = new byte[hexString.Length / 2];
for (int i = 0; i < hexString.Length / 2; i++)
hexBytes[i] = Convert.ToByte(hexString.Substring(2 * i, 2), 16);
string plainString = Encoding.ASCII.GetString(hexBytes);
Console.WriteLine(plainString); // Result: "MiFare v1.1.3"
Just, probably, should be needed to define correct Encoding.

Convert byte array to collection of enums in C#

I have a byte array that recevies enums in little endianess byte order from a function GetData() and I want to convert the array into a collection of enums.
How would I copy and cast the bytes in LE order to the enum values in C#? I have a C++ background and not too familiar with the language.
This is a sample code snippet:
public enum BarID
{
TAG0 = 0x0B01,
TAG1 = 0x0B02,
}
public class TestClass
{
List<BarID> ids;
internal TestClass()
{
ids = new List<BarID>();
byte[] foo = GetData(); // returns 01 0b 00 00 02 0b 00 00
// cast byte array so that ids contains the enums 'TAG0' and 'TAG1'
}
}
The interesting step here is reading the bytes reliably in a little-endian way (where "reliable" here means "works on any CPU, not just one that happens to be little-endian itself"); fortunately, BinaryPrimitives makes this obvious, giving you an int from a Span<byte> (the byte[] from GetData() is implicitly castable to Span<byte>). Then from the int you can just cast to BarID:
Span<byte> foo = GetData();
var result = new BarID[foo.Length / 4];
for (int i = 0; i < result.Length; i++)
{
result[i] = (BarID)BinaryPrimitives.ReadInt32LittleEndian(foo.Slice(4 * i));
}
The Slice step here just offsets where we should start reading in the span.
Though Marc's answer is both good and fast, that works only on .NET Core, or if you use additional nugets. If that could be a problem (or you target older Framework versions) you can use a solution like this:
var bytes = new byte[] { 0x01, 0x0b, 0x00, 0x00, 0x02, 0x0b, 0x00, 0x00 };
return BitConverter.IsLittleEndian
? ConvertLittleEndian(bytes)
: ConvertBigEndian(bytes);
Where the conversion methods:
private static unsafe BarID[] ConvertLittleEndian(byte[] bytes)
{
var barIds = new BarID[bytes.Length / 4];
fixed (byte* pBytes = bytes)
{
BarID* asIds = (BarID*)pBytes;
for (int i = 0; i < barIds.Length; i++)
barIds[i] = asIds[i];
}
return barIds;
}
If you know that your code will be used on little endian CPUs (eg. it is meant to be a Windows app), then you don't even need the big endian version:
private static BarID[] ConvertBigEndian(byte[] bytes)
{
var barIds = new BarID[bytes.Length / 4];
for (int i = 0; i < barIds.Length; i++)
{
int offset = i * 4;
barIds[i] = (BarID)((bytes[offset] << 3) | (bytes[offset + 1] << 2)
| (bytes[offset + 2] << 1) | bytes[offset + 3]);
}
return barIds;
}
Try this:
var foo = new byte[] {0x01, 0x0b, 0x00, 0x00, 0x02, 0x0b, 0x00, 0x00}.ToList();
IEnumerable<byte> bytes;
var result = new List<BarID>();
while ((bytes = foo.Take(4)).Any())
{
var number = BitConverter.IsLittleEndian
? BitConverter.ToInt32(bytes.ToArray(), 0)
: BitConverter.ToInt32(bytes.Reverse().ToArray(), 0);
var enumValue = (BarID) number;
result.Add(enumValue);
foo = foo.Skip(4).ToList();
}
It is not clear if the array values are grouped by two or four, however the pattern is basically the same:
public enum BarID
{
TAG0 = 0x0B01,
TAG1 = 0x0B02,
}
public class TestClass
{
List<BarID> ids;
internal TestClass()
{
ids = new List<BarID>();
byte[] foo = GetData(); // returns 01 0b 00 00 02 0b 00 00
// cast byte array so that ids contains the enums 'TAG0' and 'TAG1'
//create a hash-set with all the enum-valid values
var set = new HashSet<int>(
Enum.GetValues(typeof(BarID)).OfType<int>()
);
//scan the array by 2-bytes
for (int i = 0; i < foo.Length; i += 2)
{
int value = foo[i] + foo[i + 1] << 8;
if (set.Contains(value))
{
ids.Add((BarID)value);
}
}
}
}
The set is not mandatory, but it should prevent invalid values to be casted to a tag. For instance, if the values are word-based, the 00 00 value is invalid.
As final consideration, I wouldn't do similar tasks in a class constructor: better to create the instance, then call a dedicated method to the conversion.

CRC-CCITT 16 bit Calculation in C#

I am trying to write one program for serial port communication, where i need to send data packet with CRC, I am writing this code in C# language.
Below is sample packet which receiver is expecting with CRC.
10 02 B1 F0 3F 32 08 00 00 10 03 B4 5C
Second Data Packet : 10 02 B1 F0 3F 32 07 00 00 10 03 4D EE
10 - DLE Code
02 - STX
B1 F0 3F 32 08 00 00 are Data
10 - DLE
03 -ETX
B4 - CRC Lower Bye
5C - CRC -Upper Bye
CCIT : (Fx) = x16 + x12 + x5 + 1
Operational Initial Value: FFFFH
I tried some online CRC calculators but so far no luck, can anybody guide how to calculate CRC for above data(B1 F0 3F 32 08 00 00)? may be can suggest online calculator which can give me above output(B4 5C).
Thanks for your advise!
I found something that works, but it seems a bit strange.
First I xor'ed the two samples
10 02 B1 F0 3F 32 08 00 00 10 03 B4 5C
10 02 B1 F0 3F 32 07 00 00 10 03 4D EE
--------------------------------------
00 00 00 00 00 00 0F 00 00 00 00 F9 B2
This eliminates the initial CRC and final xor values, and led to using a bit reflected 0x11021 CRC. It appears that the CRC is using 8 bytes of data, including the trailing 0x10.
Using the CRC calculator linked to below, pick any CRC16, then click on custom and set parameters to: input reflected checked, output reflected checked, poly = 0x1021. There's not enough information to determine the initial value and final xor value without a different sized message. Using 8 bytes of data, some example options are: initial value = 0x5B08, final xor value = 0x0000, or initial value = 0xffff, final xor value = 0xdde5, or initial value = 0x0000, final xor value = 0xa169.
When using reflected parameters, the calculator bit reverses the init value (0x5B08 is 0x17DA bit reversed). For code, the 3 combos are {0x17da,0x0000}, (0xffff,0xdde5}, {0x0000,0xa169}. Poly = 0x8408 and is right shifting.
Using xx's to indicate ingored data, I got
xx xx B1 F0 3F 32 08 00 00 10 xx B4 5C
xx xx B1 F0 3F 32 07 00 00 10 xx 4D EE
Since the first two bytes are {10 02}, fixed values, they could be included, by changing the initial value. However, I wasn't able to include the ETX 03 value.
http://www.sunshine2k.de/coding/javascript/crc/crc_js.html
Second hit I've found on the web but I copied it's contents here for reference:
using System;
public enum InitialCrcValue { Zeros, NonZero1 = 0xffff, NonZero2 = 0x1D0F }
public class Crc16Ccitt {
const ushort poly = 4129;
ushort[] table = new ushort[256];
ushort initialValue = 0;
public ushort ComputeChecksum(byte[] bytes) {
ushort crc = this.initialValue;
for(int i = 0; i < bytes.Length; ++i) {
crc = (ushort)((crc << 8) ^ table[((crc >> 8) ^ (0xff & bytes[i]))]);
}
return crc;
}
public byte[] ComputeChecksumBytes(byte[] bytes) {
ushort crc = ComputeChecksum(bytes);
return BitConverter.GetBytes(crc);
}
public Crc16Ccitt(InitialCrcValue initialValue) {
this.initialValue = (ushort)initialValue;
ushort temp, a;
for(int i = 0; i < table.Length; ++i) {
temp = 0;
a = (ushort)(i << 8);
for(int j = 0; j < 8; ++j) {
if(((temp ^ a) & 0x8000) != 0) {
temp = (ushort)((temp << 1) ^ poly);
} else {
temp <<= 1;
}
a <<= 1;
}
table[i] = temp;
}
}
}
The original link: http://sanity-free.org/133/crc_16_ccitt_in_csharp.html

Calculating the PPP Frame Check Sequence

I'm attempting to generate a valid PPP Frame Check Sequence (FCS) using C#. The code I have implemented is based off of this answer.
public static class Crc16
{
const ushort polynomial = 0x8408;
static readonly ushort[] fcstab = new ushort[256];
// This is the fcstab from RFC1662
// https://www.rfc-editor.org/rfc/rfc1662#ref-7
//static readonly ushort[] fcstab = new ushort[] {
// 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
// 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7,
// 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e,
// 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876,
// 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd,
// 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5,
// 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c,
// 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974,
// 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb,
// 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3,
// 0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a,
// 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72,
// 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9,
// 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1,
// 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738,
// 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70,
// 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7,
// 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff,
// 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036,
// 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e,
// 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5,
// 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd,
// 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134,
// 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c,
// 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3,
// 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb,
// 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232,
// 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a,
// 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1,
// 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9,
// 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330,
// 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78
// };
static Crc16()
{
ushort value;
ushort temp;
for (ushort i = 0; i < fcstab.Length; ++i)
{
value = 0;
temp = i;
for (byte j = 0; j < 8; ++j)
{
if (((value ^ temp) & 0x0001) != 0)
{
value = (ushort)((value >> 1) ^ polynomial);
}
else
{
value >>= 1;
}
temp >>= 1;
}
fcstab[i] = value;
}
}
/// <summary>Method that computes the checksum.</summary>
/// <param name="buff">The input <see cref="byte[]"/> to calculate the checksum off of.</param>
/// <example>
/// byte[] fcs = Crc16.ComputeChecksumBytes(buff)
/// </example>
/// <returns></returns>
public static byte[] ComputeChecksumBytes(byte[] buff)
{
ushort fcs = 0xFFFF;
for (int i = 0; i < buff.Length; i++)
{
byte index = (byte)((fcs ^ buff[i]) & 0xff);
fcs = (ushort)((fcs >> 8) ^ fcstab[index]);
}
fcs ^= 0xFFFF;
var lsb = (fcs >> 8) & 0xff;
var msb = fcs & 0xff;
return new byte[] { (byte)msb, (byte)lsb };
}
}
The good part is that the FCS table (fcstab[]) that gets generated is the same table seen in RFC 1662 thus confirming that the code in the constructor is correct.
The problem seems to be with the ComputeChecksumBytes() method.
I have an input PPP Packet of 7E FF 03 C0 21 01 00 00 0E 02 06 00 00 00 00 07 02 08 02 DD 31 7E.
I know from this link that the "FCS is calculated over the entire PPP packet, not including the start and stop flags (7E)." This leaves me with FF 03 C0 21 01 00 00 0E 02 06 00 00 00 00 07 02 08 02 DD 31.
I also know from that link that the FCS octets (DD 31) are to be "made equal to zero". This leaves me with FF 03 C0 21 01 00 00 0E 02 06 00 00 00 00 07 02 08 02 00 00.
When I call Crc16.ComputeChecksumBytes with that input byte array, my actual calculated FCS ends up being C0 0E.
Everything I'm doing seems to be correct but I still cannot figure out why I'm not getting the DD 31 that was calculated in the original packet.
Any help would be greatly appreciated!
Just do it without the two 0's at the end.

How to convert byte[] to that text format?

I can say I don't know what I'm asking for help,because I don't know the format,but I've got a picture.
I have a byte[] array ,how do I convert it to that format below(in right)?
alt text http://img512.imageshack.us/img512/3548/48667724.jpg
Its not plain ascii.
It sounds like you'd like to take an array of bytes, and convert it to text (replacing characters outside of a certain range with "."s)
static public string ConvertFromBytes(byte[] input)
{
StringBuilder output = new StringBuilder(input.Length);
foreach (byte b in input)
{
// Printable chars are from 0x20 (space) to 0x7E (~)
if (b >= 0x20 && b <= 0x7E)
{
output.Append((char)b);
}
else
{
// This isn't a text char, so use a placehold char instead
output.Append(".");
}
}
return output.ToString();
}
or as a LINQy extension method (inside a static extension class):
static public string ToPrintableString(this byte[] bytes)
{
return Encoding.ASCII.GetString
(
bytes.Select(x => x < 0x20 || x > 0x7E ? (byte)'.' : x)
.ToArray()
);
}
(You could call that like string printable = byteArray.ToPrintableString();)
Use b.ToString("x2") to format a byte value into a two character hexadecimal string.
For the ASCII display, check if the value corresponds to a regular printable character and convert it if it is:
if (b >= 32 && b <= 127) {
c = (char)b;
} else {
c = '.';
}
Or shorter:
c = b >= 32 && b <= 127 ? (char)b : '.';
To do it on an array:
StringBuilder builder = new StringBuilder();
foreach (b in theArray) {
builder.Append(b >= 32 && b <= 127 ? (char)b : '.');
}
string result = builder.ToString();
This could be any number of encodings... try this test test script to see which of them print out:
Bl8s
Here is the script:
byte[] b = new byte[] {0x42, 0x6C, 0x38, 0x73 };
foreach (EncodingInfo ei in Encoding.GetEncodings())
{
Console.WriteLine("{0} - {1}", ei.GetEncoding().GetString(b), ei.Name);
}
[edit 2018:] Re-wrote the function from scratch to make the code much more efficient and fix some other problems. You can now also optionally specify a starting offset and number of bytes (starting from there) to display.
If you want the whole memory display, including the offset number, and left and right displays, you can do it like this: (32-byte width)
/// <summary> Returns a String where the specified bytes are formatted in a
/// 3-section debugger-style aligned memory display, 32-bytes per line </summary>
public static unsafe String MemoryDisplay(byte[] mem, int i_start = 0, int c = -1)
{
if (mem == null)
throw new ArgumentNullException();
if (i_start < 0)
throw new IndexOutOfRangeException();
if (c == -1)
c = mem.Length - i_start;
else if (c < 0)
throw new ArgumentException();
if (c == 0)
return String.Empty;
char* pch = stackalloc Char[32]; // for building right side at the same time
var sb = new StringBuilder((c / 32 + 1) * 140); // exact pre-allocation
c += i_start;
for (int i = i_start & ~0x1F; i < c;)
{
sb.Append(i.ToString("x8"));
sb.Append(' ');
do
{
if (i < i_start || i >= c) // non-requested area, or past the end
{
sb.Append(" ");
pch[i & 0x1F] = ' ';
}
else
{
var b = mem[i];
sb.Append(b.ToString("x2") + " ");
pch[i & 0x1F] = non_monospace(b) ? '.' : (Char)b;
}
}
while ((++i & 0x1F) != 0);
sb.Append(' ');
sb.AppendLine(new String(pch, 0, 32));
}
return sb.ToString();
}
The code uses the following helpers to determine which characters should be shown as 'dots' in right-hand part.
static readonly ulong[] _nmb =
{
0x00000000ffffe7ffUL,
0x8000000000000000UL,
0x00002000ffffffffUL,
0x0000000000000000UL,
};
static bool non_monospace(byte b) => (_nmb[b >> 6] & 1UL << b) != 0;
Output of the above function looks like this (character width is 138 columns, scroll to the right to see the "human-readable" part):
00000000 47 49 46 38 39 61 0f 00 0f 00 91 ff 00 00 00 00 c0 c0 c0 ff ff 00 00 00 00 21 f9 04 01 00 00 01 GIF89a...................!......
00000020 00 2c 00 00 00 00 0f 00 0f 00 00 02 2c 8c 0d 99 c7 91 02 e1 62 20 5a 79 ea bd 00 6d 89 69 8a f8 .,..........,.......b Zy...m.i..
00000040 08 e5 a7 99 e9 17 9d ac 24 a2 21 68 89 1e ac b4 d9 db 51 ab da c8 8c 1a 05 00 3b ........$.!h......Q.......;
Try: Encoding.Default.GetBytes
If that doesn't work, there are different types that you can specify (UTF-8, ASCII...)

Categories