Converting array value to hex in C# - c#

How can I convert array[1] to hexadecimal in C#
array[1] = 1443484
I have tried the following but it doesn't compile:
StringBuilder hex = new StringBuilder(array[1].Length * 2);
foreach (byte b in array[1])
hex.AppendFormat("{0:x2}", b);
string value = hex.ToString();

If you want just to obtain hexadecimal representation, you can do it in one go:
// 16069c
string value = Convert.ToString(array[1], 16);
Or
string value = array[1].ToString("x");
Or (padded version: at least 8 characters)
// 0016069c
string value = array[1].ToString("x8");
If you want to manipulate with bytes try BitConverter class
byte[] bytes = BitConverter.GetBytes(array[1]);
string value = string.Concat(bytes.Select(b => b.ToString("x2")));
Your code amended:
using System.Runtime.InteropServices; // For Marshal
...
// Marshal.SizeOf - length in bytes (we don't have int.Length in C#)
StringBuilder hex = new StringBuilder(Marshal.SizeOf(array[1]) * 2);
// BitConverter.GetBytes - byte[] representation
foreach (byte b in BitConverter.GetBytes(array[1]))
hex.AppendFormat("{0:x2}", b);
// You can well get "9c061600" (reversed bytes) instead of "0016069c"
// if BitConverter.IsLittleEndian == true
string value = hex.ToString();

Related

Convert a binary string to int c#

I have this code:
string result = "";
foreach(char item in texte)
{
result += Convert.ToString(item, 2).PadLeft(8, '0');
}
So I have string named result which is conversion of a word like 'bonjour' in binary.
for texte = "bonjour" I have string result = 01100010011011110110111001101010011011110111010101110010 as type integer.
And when I do
Console.writeLine(result[0])
I obtain 0, normal, what I expected, but if I do
Console.WriteLine((int)result[0])
or
Console.WriteLine(Convert.ToInt32(result[0]))
I obtain 48!
I don't want 48, I want 0 or 1 at the type integer.
Could you help me please?
You can just subtract 48 from it!
Console.WriteLine(result[0] - 48);
because the characters digits 0-9 are encoded as 48 to 57.
If you want to access each bit by index, I suggest using a BitArray instead:
var bytes = Encoding.ASCII.GetBytes("someString");
var bitArray = new BitArray(bytes);
// now you can access the first bit like so:
bitArray.Get(0) // this returns a bool
bitArray.Get(0) ? 1 : 0 // this gives you a 1 or 0
string a = "23jlfdsa890123kl21";
byte[] data = System.Text.Encoding.Default.GetBytes(a);
StringBuilder result = new StringBuilder(data.Length * 8);
foreach (byte b in data)
{
result.Append(Convert.ToString(b, 2).PadLeft(8, '0'));
}
you can try this code.
Just Do this
Console.WriteLine(Convert.ToInt32(Convert.ToString(result[0])));
You're expecting it to behave the same as Convert.ToInt32(string input) but actually you're invoking Convert.ToInt32(char input) and if you check the docs, they explicitly state it will return the unicode value (in this case the same as the ASCII value).
http://msdn.microsoft.com/en-us/library/ww9t2871(v=vs.110).aspx

Unicode Hex String to String

I have a unicode string like this:
0030003100320033
Which should turn into 0123.
This is a simple case of 0123 string, but there are some string and unicode chars as well. How can I turn this type of unicode hex string to string in C#?
For normal US charset, first part is always 00, so 0031 is "1" in ASCII, 0032 is "2" and so on.
When its actual unicode char, like Arabic and Chinese, first part is not 00, for instance for Arabic its 06XX, like 0663.
I need to be able to turn this type of Hex string into C# decimal string.
There are several encodings that can represent Unicode, of which UTF-8 is today's de facto standard. However, your example is actually a string representation of UTF-16 using the big-endian byte order. You can convert your hex string back into bytes, then use Encoding.BigEndianUnicode to decode this:
public static void Main()
{
var bytes = StringToByteArray("0030003100320033");
var decoded = System.Text.Encoding.BigEndianUnicode.GetString(bytes);
Console.WriteLine(decoded); // gives "0123"
}
// https://stackoverflow.com/a/311179/1149773
public static byte[] StringToByteArray(string hex)
{
byte[] bytes = new byte[hex.Length / 2];
for (int i = 0; i < hex.Length; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
Since Char in .NET represents a UTF-16 code unit, this answer should give identical results to Slai's, including for surrogate pairs.
Shorter less efficient alternative:
Regex.Replace("0030003100320033", "....", m => (char)Convert.ToInt32(m + "", 16) + "");
You should try this solution
public static void Main()
{
string hexString = "0030003100320033"; //Hexa pair numeric values
//string hexStrWithDash = "00-30-00-31-00-32-00-33"; //Hexa pair numeric values separated by dashed. This occurs using BitConverter.ToString()
byte[] data = ParseHex(hexString);
string result = System.Text.Encoding.BigEndianUnicode.GetString(data);
Console.Write("Data: {0}", result);
}
public static byte[] ParseHex(string hexString)
{
hexString = hexString.Replace("-", "");
byte[] output = new byte[hexString.Length / 2];
for (int i = 0; i < output.Length; i++)
{
output[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
return output;
}

How to convert string array to byte array in c#

So i have a string
string enc = ""hx0.+dhx0-pdhx0pzdhx0xx";
This is encrypted and when decrypted has the hexadecimal values, the starting values are
"0xfc,0xe8,0x82,0x00"
Then this
string decrypted = encryptDecrypt(enc);
then this
then i divided it after every comma to with the split command
string[] hi = decrypted.Split(',');
When i check using this code
foreach (var item in hi )
{
Console.WriteLine(item.ToString());
}
it shows all the hexadecimal in side it
i want to turn string array values which are
0xfc,0xe8,0x82,0x00 and more into byte array values which are
0xfc,0xe8,0x82,0x00 too not some other values
Is that the only string, or does that value change? Does your array need to be dynamic?
string [] arrayString = new string []; //Your Array.
byte [] arrayByte = new byte[arrayString.Length];
for (int i = 0; i < arrayString.Length; i++)
{
arrayByte[i] = Convert.ToByte(arrayString[i], 16);
}
Sample input:
String[] hi = "00,01,fe,ff".Split(',');
Conversion using a lambda function to convert each hexadecimal string to a byte:
Byte[] b = Array.ConvertAll(hi, h => Convert.ToByte(h, 16));
If you want a different kind of delegate:
Byte[] b = Array.ConvertAll(hi, HexToByte);
private Byte HexToByte(String h)
{
return Convert.ToByte(h, 16);
}
Same, with an expression-bodied function:
Byte[] b = Array.ConvertAll(hi, HexToByte);
private Byte HexToByte(String h) => Convert.ToByte(h, 16);
Or yet a different kind of delegate:
Converter<String, Byte> hexToByte = h => Convert.ToByte(h, 16);
Byte[] b = Array.ConvertAll(hi, hexToByte);
Array.ConvertAll is doing the real work. Conversion from hex is either a trivial idea that can be done inline or an important idea that can be given a name and/or a full implementation block.
Convert each of the strings into byte and then store it to str variable.
byte[,] str = new byte[50,50];
int i = 0;
foreach (var item in hi)
{
Console.WriteLine(item.ToString());
byte[] arr = Encoding.ASCII.GetBytes(item.ToString());
str[i] = arr;
i++;
}
For more information, see this link
For some text is not Ascii that you can use Utf-8 to convert string to byte.
System.Text.Encoding.UTF8.GetBytes(item);
To convert from a string to a byte array, you can use the GetBytes method:
System.Text.Encoding.ASCII.GetBytes(item);

How to sum existing byte array value with another HEX value in C#?

i need to decode a string in C#. Algorithm peformed in HEX values. So in C# i think i need to convert to byte array?am i right?. So I did a byte array from a string:
string Encoded = "ENCODEDSTRINGSOMETHING";
byte[] ba = Encoding.Default.GetBytes (Encoded);
Now i need to modify each byte in byte array first starting from summing hex value (0x20) to first byte and for the each next byte in array i should substitute 0x01 hex from starting 0x20 hex value and sum it with following bytes in my ba array. Then i need to convert my byte array result to string again and print. In Python this is very easy:
def decode ():
strEncoded = "ENCODEDSTRINGSOMETHING"
strDecoded = ""
counter = 0x20
for ch in strEncoded:
ch_mod = ord(ch) + counter
counter -= 1
strDecoded += chr(ch_mod)
print ("%s" % strDecoded)
if __name__ == '__main__':
decode()
How can i do it in C#? Thank you very much.
Here's a rough outline of how to do what you are trying to do. Might need to change it a bit to fit your problem/solution.
public string Encode(string input, int initialOffset = 0x20)
{
string result = "";
foreach(var c in input)
{
result += (char)(c + (initialOffset --));
}
return result;
}
Try this code:
string Encoded = "ENCODEDSTRINGSOMETHING";
byte[] ba = Encoding.Default.GetBytes(Encoded);
string strDecoded = "";
int counter = 0x20;
foreach (char c in Encoded)
{
int ch_mod = (int)c+counter;
counter -= 1;
strDecoded += (char)ch_mod;
}

Hex change low to high and then conever to decimal

I have Hex string like 1480D604. Which I need to change order from Low to High 0x04D68014 and then I need to cast it into decimal value. One approach that I can think is first change their order first like.
Step 1 : 14-80-D6-04 --> 04-D6-80-14
How can I change this order from Low to High order in hex value.
Step 2
Cast output from first step into decimal value like this
int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
0x04D68014=81166356
Is there any simple way to achieve this in single step.
The only way to do it in a "single step" is to define a method, use the BitConverter:
public static int ReverseByteOrder(int value)
{
byte[] bytes = BitConverter.GetBytes(value);
Array.Reverse(bytes);
return BitConverter.ToInt32(bytes, 0);
}
Usage:
int value = 0x1480D604; //or parse from string
int decValue = ReverseByteOrder(value);
//decValue = 0x04D68014
IsLittleEndian
Strictly speaking, you should look at BitConverter.IsLittleEndian as it is possible that the order is already in the correct order, depending on the system it's running on.
This is very unlikely, so I wouldn't bother coding to that case, but I would at the very least cause the program to fall over if run on a system where BitConverter.IsLittleEndian is not true.
You can do it by reversing a byte array. So first convert your string to byte array with this method:
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
Use like:
string hexString = "1480D604";
byte[] byteArray = StringToByteArray(hexString);
Then reverse the byte array:
Array.Reverse(byteArray);
Then convert it back to hex string again with the method:
public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
Using like:
string reversedString = ByteArrayToString(byteArray);
And finally convert it to int as you mentioned:
int decValue = int.Parse(reversedString, System.Globalization.NumberStyles.HexNumber);
And that's it. Hope it helps.

Categories