How to convert decimal string value to hex byte array in C#? - c#

I have an input string which is in decimal format:
var decString = "12345678"; // in hex this is 0xBC614E
and I want to convert this to a fixed length hex byte array:
byte hexBytes[] // = { 0x00, 0x00, 0xBC, 0x61, 0x4E }
I've come up with a few rather convoluted ways to do this but I suspect there is a neat two-liner! Any thoughts? Thanks
UPDATE:
OK I think I may have inadvertently added a level of complexity by having the example showing 5 bytes. Maximum is in fact 4 bytes (FF FF FF FF) = 4294967295. Int64 is fine.

If you have no particular limit to the size of your integer, you could use BigInteger to do this conversion:
var b = BigInteger.Parse("12345678");
var bb = b.ToByteArray();
foreach (var s in bb) {
Console.Write("{0:x} ", s);
}
This prints
4e 61 bc 0
If the order of bytes matters, you may need to reverse the array of bytes.
Maximum is in fact 4 bytes (FF FF FF FF) = 4294967295
You can use uint for that - like this:
uint data = uint.Parse("12345678");
byte[] bytes = new[] {
(byte)((data>>24) & 0xFF)
, (byte)((data>>16) & 0xFF)
, (byte)((data>>8) & 0xFF)
, (byte)((data>>0) & 0xFF)
};
Demo.

To convert the string to bytes you can use BitConverter.GetBytes:
var byteArray = BitConverter.GetBytes(Int32.Parse(decString)).Reverse().ToArray();
Use the appropriate type instead of Int32 if the string is not allways an 32 bit integer.
Then you could check the lenght and add padding bytes if needed:
if (byteArray.Length < 5)
{
var newArray = new byte[5];
Array.Copy(byteArray, 0, newArray, 5 - byteArray.Length, byteArray.Length);
byteArray = newArray;
}

You can use Linq:
String source = "12345678";
// "BC614E"
String result = String.Join("", BigInteger
.Parse(source)
.ToByteArray()
.Reverse()
.SkipWhile(item => item == 0)
.Select(item => item.ToString("X2")));
In case you want Byte[] it'll be
// [0xBC, 0x61, 0x4E]
Byte[] result = BigInteger
.Parse(source)
.ToByteArray()
.Reverse()
.SkipWhile(item => item == 0)
.ToArray();

Related

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.

Replace Hex String in File

After banging my head on it for hours, I am at my wits end. I have a hex string in a file that is "68 39 30 00 00". The "39 30" is the decimal value "12345" which I am wanting to replace, and the "68" and "00 00" are just to ensure there is a single match.
I want to pass in a new decimal value such as "12346", and replace the existing value in the file. I have tried converting everything back and fourth between hex, byte arrays, and so on and feel it has to be much simpler than I am making it out to be.
static void Main(string[] args)
{
// Original Byte string to find and Replace "12345"
byte[] original = new byte[] { 68, 39, 30, 00, 00 };
int newPort = Convert.ToInt32("12346");
string hexValue = newPort.ToString("X2");
byte[] byteValue = StringToByteArray(hexValue);
// Build Byte Array of the port to replace with. Starts with /x68 and ends with /x00/x00
byte[] preByte = new byte[] { byte.Parse("68", System.Globalization.NumberStyles.HexNumber) };
byte[] portByte = byteValue;
byte[] endByte = new byte[] { byte.Parse("00", System.Globalization.NumberStyles.HexNumber), byte.Parse("00", System.Globalization.NumberStyles.HexNumber) };
byte[] replace = new byte[preByte.Length + portByte.Length + endByte.Length];
preByte.CopyTo(replace, 0);
portByte.CopyTo(replace, preByte.Length);
endByte.CopyTo(replace, (preByte.Length + portByte.Length));
Patch("Server.exe", "Server1.exe", original, replace);
}
static private byte[] StringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
The decimal value of 39 30 is 14640 so it will check for the 14640 which is not present.
Hex value for 12345 is 30 39. Just correct the values and your program will work fine.

trim hex from end of string

I have a byte array that's been initialized with 0xFF in each byte:
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = 0xFF;
}
Once this byte array has been filled with valid data, I need to extract an ASCII string that's stored at offset 192 and may be up to 32 characters in length. I'm doing this like so:
ASCIIEncoding enc = new ASCIIEncoding();
stringToRead = enc.GetString(buffer, 192, 32);
This works but I need to strip off the trailing bytes that contain 0xFF to avoid the string looking something like "John Smith??????????????????????". Is there a function in .NET that provides this ability? Something like the String.TrimEnd() function perhaps or am I looking at a regex to do this?
I would suggest just finding out how long the string will really be:
int firstFF = Array.IndexOf(buffer, (byte) 0xff, 192);
if (firstFF == -1)
{
firstFF = buffer.Length;
}
stringToRead = Encoding.ASCII(buffer, 192, firstFF - 192);
I would not try to give Encoding.ASCII bytes which aren't valid ASCII-encoded text. I don't know offhand what it would do with them - I suspect it would convert them to ? to show the error (as suggested by your existing output), but then you wouldn't be able to tell the difference between that and real question marks. For example:
byte[] data = { 0x41, 0x42, 0x43, 0xff, 0xff };
string text = Encoding.ASCII.GetString(data);
Console.WriteLine(text.Contains((char) 0xff)); // False
Console.WriteLine(text.TrimEnd((char) 0xff).Length); // Still 5...
Now you could create an encoding which used some non-ASCII replacement character... but that's a lot of hassle when you can just find where the binary data stops being valid.
var s = "Whatever" + new String((Char)0xFF, 32);
var trimmed = s.TrimEnd((Char)0xFF);
Alternatively, you can scan the string for the first index of the character, then take the substring:
var index = s.IndexOf((Char)0xFF);
var trimmed = s.Substring(0, index);

Convert byte array to int

I am trying to do some conversion in C#, and I am not sure how to do this:
private int byteArray2Int(byte[] bytes)
{
// bytes = new byte[] {0x01, 0x03, 0x04};
// how to convert this byte array to an int?
return BitConverter.ToInt32(bytes, 0); // is this correct?
// because if I have a bytes = new byte [] {0x32} => I got an exception
}
private string byteArray2String(byte[] bytes)
{
return System.Text.ASCIIEncoding.ASCII.GetString(bytes);
// but then I got a problem that if a byte is 0x00, it show 0x20
}
Could anyone give me some ideas?
BitConverter is the correct approach.
Your problem is because you only provided 8 bits when you promised 32. Try instead a valid 32-bit number in the array, such as new byte[] { 0x32, 0, 0, 0 }.
If you want an arbitrary length array converted, you can implement this yourself:
ulong ConvertLittleEndian(byte[] array)
{
int pos = 0;
ulong result = 0;
foreach (byte by in array) {
result |= ((ulong)by) << pos;
pos += 8;
}
return result;
}
It's not clear what the second part of your question (involving strings) is supposed to produce, but I guess you want hex digits? BitConverter can help with that too, as described in an earlier question.
byte[] bytes = { 0, 0, 0, 25 };
// If the system architecture is little-endian (that is, little end first),
// reverse the byte array.
if (BitConverter.IsLittleEndian)
Array.Reverse(bytes);
int i = BitConverter.ToInt32(bytes, 0);
Console.WriteLine("int: {0}", i);
this is correct, but you're
missing, that Convert.ToInt32
'wants' 32 bits (32/8 = 4 bytes)
of information to make a conversion,
so you cannot convert just One byte:
`new byte [] {0x32}
absolutely the the same trouble
you have. and do not forget about
the encoding you use: from encoding to encoding you have 'different byte count per symbol'
A fast and simple way of doing this is just to copy the bytes to an integer using Buffer.BlockCopy:
UInt32[] pos = new UInt32[1];
byte[] stack = ...
Buffer.BlockCopy(stack, 0, pos, 0, 4);
This has the added benefit of being able to parse numerous integers into an array just by manipulating offsets..

How to convert a String to a Hex Byte Array? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How do you convert Byte Array to Hexadecimal String, and vice versa, in C#?
For testing my encryption algorithm I have being provided keys, plain text and their resulting cipher text.
The keys and plaintext are in strings
How do i convert it to a hex byte array??
Something like this : E8E9EAEBEDEEEFF0F2F3F4F5F7F8F9FA
To something like this :
byte[] key = new byte[16] { 0xE8, 0xE9, 0xEA, 0xEB, 0xED, 0xEE, 0xEF, 0xF0, 0xF2, 0xF3, 0xF4, 0xF5, 0xF7, 0xF8, 0xF9, 0xFA} ;
Thanx in advance :)
Do you need this?
static class HexStringConverter
{
public static byte[] ToByteArray(String HexString)
{
int NumberChars = HexString.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(HexString.Substring(i, 2), 16);
}
return bytes;
}
}
Hope it helps.
Sample code from MSDN:
string hexValues = "48 65 6C 6C 6F 20 57 6F 72 6C 64 21";
string[] hexValuesSplit = hexValues.Split(' ');
foreach (String hex in hexValuesSplit)
{
// Convert the number expressed in base-16 to an integer.
int value = Convert.ToInt32(hex, 16);
// Get the character corresponding to the integral value.
string stringValue = Char.ConvertFromUtf32(value);
char charValue = (char)value;
Console.WriteLine("hexadecimal value = {0}, int value = {1}, char value = {2} or {3}", hex, value, stringValue, charValue);
}
You only have to change it to split the string on every 2 chars instead of on spaces.
did u mean this
StringBuilder Result = new StringBuilder();
string HexAlphabet = "0123456789ABCDEF";
foreach (byte B in Bytes)
{
Result.Append(HexAlphabet[(int)(B >> 4)]);
Result.Append(HexAlphabet[(int)(B & 0xF)]);
}
return Result.ToString();

Categories