How to change byte[] to hex? [duplicate] - c#

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
How do you convert Byte Array to Hexadecimal String, and vice versa, in C#?
C# byte[] to hex string
I need to take this:
byte[] data = new byte[] { 1, 2, 3, 4 }
And turn it into something like this:
0x01020304
What is the best way to do this in C#?

StringBuilder sb = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
{
sb.AppendFormat("{0:x2}", b)
}
return sb.ToString();

For a single value:
String.Format("{0:X2}", value);
Depending on what the array represents you can then do some string concatenating to put all the bits together.

Related

Cast string to hex byte array [duplicate]

This question already has answers here:
How do you convert a byte array to a hexadecimal string, and vice versa?
(53 answers)
Converting string to byte array in C#
(20 answers)
Closed 2 years ago.
I need to cast a string to a byte array in hex representation.
For example:
Value: 06000002
What I need is:
30 36 30 30 30 30 30 32
I tried to implicit convert all chars to byte as following:
byte[] bytes = new byte[daten.Length];
for (int i = 0; i < daten.Length; i++)
{
int value = Convert.ToInt32(daten[i]);
bytes[i] = (byte)daten[i];
}
However I always get this result:
48 54 48 48 48 48 48 50
I do not need the result as string! I need it as byte array!
How do achive this?
All you should need is:
var value = "06000002";
byte[] bytes = Encoding.UTF8.GetBytes(value);
In .NET 5 you can then use
string hexString = Convert.ToHexString(bytes);
To verify your result is what you expected
3036303030303032
https://dotnetfiddle.net/6sUmgE
To get the desired output, you can convert each character to its hex representation:
var s = "06000002";
var bytes = s.Select(c => (byte) c);
var hexCodes = bytes.Select(b => b.ToString("X2"));
You could stop here, or perhaps convert it to an Array or List.
Note that bytes are just numbers, there is no such thing as "hex bytes". The only time where "hex" exists is after conversion to string format, as I did above.
To still get it as one string you can proceed with this:
var result = string.Join(' ', hexCodes);
Or all in one go:
var result = string.Join(' ', "06000002".Select(c => ((byte) c).ToString("X2")));

How to convert byte[512] to string 1024 length [duplicate]

This question already has answers here:
How do you convert a byte array to a hexadecimal string, and vice versa?
(53 answers)
Closed 5 years ago.
This bit of code produces an array of size 512, it converts a string that was originally 1024 characters in length and has hex data.
byte[] content = Enumerable.Range(0, data.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(data.Substring(x, 2), 16))
.ToArray();
I like to know how to reverse this so taking a byte[512] I want to produce the 1024 length string containing the hex data.
Try with
var result = string.Join("",
inputString.Select(c => String.Format("{0:X2}", Convert.ToInt32(c))));

Convert to base 2 then split in an array [duplicate]

This question already has answers here:
Convert int to a bit array in .NET
(10 answers)
Closed 7 years ago.
I want to convert my base 10 number to base 2 and then store parts in an array.
Here are two examples:
my value is 5 so it will be converted to 101 then I have an array like this: {1,0,1}
or my value is 26 so it will be converted to 11010 then I will have an array like this: {0,1,0,1,1}
Thank you in advance for your time and consideration.
To convert the int 'x'
int x = 3;
One way, by manipulation on the int :
string s = Convert.ToString(x, 2); //Convert to binary in a string
int[] bits= s.PadLeft(8, '0') // Add 0's from left
.Select(c => int.Parse(c.ToString())) // convert each char to int
.ToArray(); // Convert IEnumerable from select to Array
Alternatively, by using the BitArray class-
BitArray b = new BitArray(new byte[] { x });
int[] bits = b.Cast<bool>().Select(bit => bit ? 1 : 0).ToArray();
Source: https://stackoverflow.com/a/6758288/1560697

Search ReadAllBytes for specific values

I am writing a program that reads '.exe' files and stores their hex values in an array of bytes for comparison with an array containing a series of values. (like a very simple virus scanner)
byte[] buffer = File.ReadAllBytes(currentDirectoryContents[j]);
I have then used BitConverter to create a single string of these values
string hex = BitConverter.ToString(buffer);
The next step is to search this string for a series of values(definitions) and return positive for a match. This is where I am running into problems. My definitions are hex values but created and saved in notepad as defintions.xyz
string[] definitions = File.ReadAllLines(#"C:\definitions.xyz");
I had been trying to read them into a string array and compare the definition elements of the array with string hex
bool[] test = new bool[currentDirectoryContents.Length];
test[j] = hex.Contains(definitions[i]);
This IS a section from a piece of homework, which is why I am not posting my entire code for the program. I had not used C# before last Friday so am most likely making silly mistakes at this point.
Any advice much appreciated :)
It is pretty unclear exactly what kind of format you use of the definitions. Base64 is a good encoding for a byte[], you can rapidly convert back and forth with Convert.ToBase64String and Convert.FromBase64String(). But your question suggests the bytes are encoded in hex. Let's assume it looks like "01020304" for a new byte[] { 1, 2, 3, 4}. Then this helper function converts such a string back to a byte[]:
static byte[] Hex2Bytes(string hex) {
if (hex.Length % 2 != 0) throw new ArgumentException();
var retval = new byte[hex.Length / 2];
for (int ix = 0; ix < hex.Length; ix += 2) {
retval[ix / 2] = byte.Parse(hex.Substring(ix, 2), System.Globalization.NumberStyles.HexNumber);
}
return retval;
}
You can now do a fast pattern search with an algorithm like Boyer-Moore.
I expect you understand that this is a very inefficient way to do it. But except for that, you should just do something like this:
bool[] test = new bool[currentDirectoryContents.Length];
for(int i=0;i<test.Length;i++){
byte[] buffer = File.ReadAllBytes(currentDirectoryContents[j]);
string hex = BitConverter.ToString(buffer);
test[i] = ContainsAny(hex, definitions);
}
bool ContainsAny(string s, string[] values){
foreach(string value in values){
if(s.Contains(value){
return true;
}
}
return false;
}
If you can use LINQ, you can do it like this:
var test = currentDirectoryContents.Select(
file=>definitions.Any(
definition =>
BitConverter.ToString(
File.ReadAllBytes(file)
).Contains(definition)
)
).ToArray();
Also, make sure that your definitions-file is formatted in a way that matches the output of BitConverter.ToString(): upper-case with dashes separating each encoded byte:
12-AB-F0-34
54-AC-FF-01-02

Operations on BitArray [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How i can convert BitArray to single int?
How can I read an integer to a BitArray(6) (assuming it can be contained) and how to convert a BitArray(6) to unsigned/signed integer.
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);
// Output: int: 25
BitArray FromInt32(Int32 a)
{
byte[] bytes = BitConverter.GetBytes(a);
return new BitArray(bytes);
}
For reverse operaton see this question as mentioned before.

Categories