I'm just starting with the c# programming and
as the heading describes, I'm looking for a way to convert a number passed to me as an ASCII character in a byte[] to an integer. I often find the way to convert a hex-byte to ASCII-char or string. I also find the other direction, get the hex-byte from a char. Maybe I should still say that I have the values displayed in a texbox for control.
as an example:
hex- code: 30 36 38 31
Ascii string: (0) 6 8 1
Integer (dez) should be: 681
so far I have tried all sorts of things. I also couldn't find it on the Microsoft Visual Studio website. Actually this should be relatively simple. I am sorry for my missing basics in c#.
Putting together this hex-to-string answer and this integer parsing answer, we get the following:
// hex -> byte array -> string
var hexBytes = "30 36 38 31";
var bytes = hexBytes.Split(' ')
.Select(hb => Convert.ToByte(hb, 16)) // converts string -> byte using base 16
.ToArray();
var asciiStr = System.Text.Encoding.ASCII.GetString(bytes);
// parse string as integer
int x = 0;
if (Int32.TryParse(asciiStr, out x))
{
Console.WriteLine(x); // write to console
}
else
{
Console.WriteLine("{0} is not a valid integer.", asciiStr); // invalid number, write error to console
}
Try it online
A typical solution of the problem is a Linq query. We should
Split initial string into items
Convert each item to int, treating item being hexadecimal. We should subtract '0' since we have not digit itself but its ascii code.
Aggregate items into the final integer
Code:
using System.Linq;
...
string source = "30 36 38 31";
int result = source
.Split(' ')
.Select(item => Convert.ToInt32(item, 16) - '0')
.Aggregate((sum, item) => sum * 10 + item);
If you want to obtain ascii string you can
Split the string
Convert each item into char
Join the chars back to string:
Code:
string source = "30 36 38 31";
string asciiString = string.Join(" ", source
.Split(' ')
.Select(item => (char)Convert.ToInt32(item, 16)));
To convert a byte array containing ASCII codes to an integer:
byte[] data = {0x30, 0x36, 0x38, 0x31};
string str = Encoding.ASCII.GetString(data);
int number = int.Parse(str);
Console.WriteLine(number); // Prints 681
To convert an integer to a 4-byte array containing ASCII codes (only works if the number is <= 9999 of course):
int number = 681;
byte[] data = Encoding.ASCII.GetBytes(number.ToString("D4"));
// data[] now contains 30h, 36h, 38h, 31h
Console.WriteLine(string.Join(", ", data.Select(b => b.ToString("x"))));
I have the following string:
string hi = "0xfc,0xe8,0x82,0x00,0x00,0x00,0x60,0x89,0xe5,0x31,0xc0,0x64,0x8b,0x50,0x30,
0x8b,0x52,0x0c,0x8b,0x52,0x14,0x8b,0x72,0x28,0x0f,0xb7,0x4a,0x26,0x31,0xff,
0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0xc1,0xcf,0x0d,0x01,0xc7,0xe2,0xf2,0x52,
0x57,0x8b,0x52,0x10,0x8b,0x4a,0x3c,0x8b,0x4c,0x11,0x78,0xe3,0x48,0x01,0xd1,
0x51,0x8b,0x59,0x20,0x01,0xd3,0x8b"
And I split it on the ',' character into an array:
string[] string1 = decrypted.Split(',');
Now I need a way to store string1 into a byte array so it looks like:
byte[] byte1 = {0xfc,0xe8,0x82,0x00,0x00,0x00,0x60,0x89,0xe5,0x31,0xc0,0x64,0x8b,0x50,0x30,
0x8b,0x52,0x0c,0x8b,0x52,0x14,0x8b,0x72,0x28,0x0f,0xb7,0x4a,0x26,0x31,0xff,
0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0xc1,0xcf,0x0d,0x01,0xc7,0xe2,0xf2,0x52,
0x57,0x8b,0x52,0x10,0x8b,0x4a,0x3c,0x8b,0x4c,0x11,0x78,0xe3,0x48,0x01,0xd1,
0x51,0x8b,0x59,0x20,0x01,0xd3,0x8b}
You can convert a single string from hex to binary using Convert.ToByte(string, int) by passing 16 as the second parameter.
With this knowledge, and a little trimming and substringing, we can convert to an array of bytes with a little LINQ:
var byteArray = input
.Split(',')
.Select
(
s => Convert.ToByte
(
s.Trim().Substring(2),
16
)
)
.ToArray();
Example on DotNetFiddle
public static 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();
}
follow the same you will get your answer
the are many ways to convert an integer to hex STRING, but is there a way to cast it to a hex literal as in?
string = z
integer = 122
hex = 0X7A
an integer remains an integer irrespective of the representation. You can assign the hex value directly to an int. The representation makes only a difference when you want to display it or use it as a string:
int integer = 122;
int integer_in_hex = 0X7A;
For the display you can use the format string "X2" which means to display the munber in hex with the length of 2 positions:
Console.WriteLine(integer_in_hex.ToString("X2"));
Console.WriteLine(integer.ToString("X2"));
the output is the same:
7A 7A
for more information please read the documentation
Are you looking for string's dump (representing characters within the string with their hex values)? Something like this:
using System.Linq;
...
string test = "hello z";
// To dump
string dump = string.Join(" ", test.Select(c => $"0x{(int)c:X2}"));
// From dump
string restore = string.Concat(dump
.Split(' ')
.Select(item => (char)Convert.ToInt32(item, 16)));
Console.WriteLine(dump);
Console.WriteLine(restore);
Outcome
0x68 0x65 0x6C 0x6C 0x6F 0x20 0x7A
hello z
I need to use HEX() in MySQL to get data out of the database and process in C# WinForm code. The binary string needs to be decoded in C#, is there an equivalent UNHEX() function?
From MySQL Doc:
For a string argument str, HEX() returns a hexadecimal string
representation of str where each byte of each character in str is
converted to two hexadecimal digits. (Multi-byte characters therefore
become more than two digits.) The inverse of this operation is
performed by the UNHEX() function.
For a numeric argument N, HEX() returns a hexadecimal string
representation of the value of N treated as a longlong (BIGINT)
number. This is equivalent to CONV(N,10,16). The inverse of this
operation is performed by CONV(HEX(N),16,10).
mysql> SELECT 0x616263, HEX('abc'), UNHEX(HEX('abc'));
-> 'abc', 616263, 'abc' mysql> SELECT HEX(255), CONV(HEX(255),16,10);
-> 'FF', 255
You can use this not-widely-known SoapHexBinary class to parse hex string
string hex = "616263";
var byteArr = System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary.Parse(hex).Value;
var str = Encoding.UTF8.GetString(byteArr);
After fetching the binary string from the database, you can "unhex" it this way:
public static string Hex2String(string input)
{
var builder = new StringBuilder();
for(int i = 0; i < input.Length; i+=2){ //throws an exception if not properly formatted
string hexdec = input.Substring(i, 2);
int number = Int32.Parse(hexdec, NumberStyles.HexNumber);
char charToAdd = (char)number;
builder.Append(charToAdd);
}
return builder.ToString();
}
The method builds a string from the hexadecimal format of the numbers, their char representation being concatenated to the builder branch.
I'm saving a bitarray (40 bits) from Python (using bitarray lib) to Redis.
When I retrieve this value from Redis, I get: \xe8\x00\x00\x00\x00
How do I convert this value to "01010101" in C#?
Thank you!
EDIT:
When i use this form:
http://easycalculation.com/hex-converter.php, the binary value returned is what i'm expecting.
You could do this:
// Chop up the string into individual hex values
string[] hexStrings = hexString.Split(new[] { "\\x" }, StringSplitOptions.RemoveEmptyEntries);
// Convert the individual hex strings into integers
int[] values = hexStrings.Select(s => Convert.ToInt32(s, 16)).ToArray();
// Convert the integers into 8-character binary strings
string[] binaryStrings = values.Select(v => Convert.ToString(v, 2).PadLeft(8, '0')).ToArray();
// Join the strings together
string binaryString = string.Join("", binaryStrings);
EDIT - Here's an example of what you could do if you want to use a BitArray:
// Chop up the string into individual hex values
string[] hexStrings = hexString.Split(new[] { "\\x" }, StringSplitOptions.RemoveEmptyEntries);
// Convert the individual hex strings into bytes
byte[] bytes = hexStrings.Select(s => Convert.ToByte(s, 16)).ToArray();
BitArray bitArray = new BitArray(bytes);