I have the following code:
string s = "2563MNBJP89256666666685755854";
Byte[] bytes = encoding.GetBytes(s);
string hex = "";
foreach (byte b in bytes)
{
int c=b;
hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(c.ToString()));
}
It prints the hex values . How can I add it in a vector ob bytes like this?
new byte [0x32,0x35..]
In hex I have : 323536....and so on. The next step is to add then in a byte[] vector in the following format 0x32,0x35..and so on; How to do this?
THX
Isn't bytes already the list of bytes you want?
C#: System.Text.Encoding.ASCII.GetBytes("test")
For C# you could try
System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(strVar);//strVar is the string variable
in C# you can use Encoding.GetBytes Method
Related
I have json string as in example below
{"SaleToPOIRequest":{"MessageHeader":{"ProtocolVersion":"2.0","MessageClass":"Service","MessageCategory":"Login","MessageType":"Request","ServiceID":"498","SaleID":"SaleTermA","POIID":"POITerm1"},"LogoutRequest":{}}}
I want to convert json request to hexadecimal. I tried example in this link but i cannot get the exact conversion because of {,:,",} values.
Actually i can get hexadecimal return but when i reconvert to string i got return as below
{"SaleToPOIReque§7B#§²$ÖW76vTVder":{"ProtocolV¦W'6öâ#¢#"ã"Â$ÚessageClass":"Se§'f6R"Â$ÖW76vT:ategory":"Login"¢Â$ÖW76vUGR#¢*Request","Servic¤B#¢#C"Â%6ÆZID":"SaleTermA",¢%ôB#¢%ôFW&Ú1"},"LogoutReque§7B#§·×
that is not usefull for me
Is there any way to convert this?
So basically the problem is not only converting to hex but also converting back.
This is nothing more then combining 2 answers already on SO:
First for converting we use the answer given here: Convert string to hex-string in C#
Then for the converting back you can use this answer:
https://stackoverflow.com/a/724905/10608418
For you it would then look something like this:
class Program
{
static void Main(string[] args)
{
var input = "{\"SaleToPOIRequest\":{\"MessageHeader\":{\"ProtocolVersion\":\"2.0\",\"MessageClass\":\"Service\",\"MessageCategory\":\"Login\",\"MessageType\":\"Request\",\"ServiceID\":\"498\",\"SaleID\":\"SaleTermA\",\"POIID\":\"POITerm1\"},\"LogoutRequest\":{}}}";
var hex = string.Join("",
input.Select(c => String.Format("{0:X2}", Convert.ToInt32(c))));
var output = Encoding.ASCII.GetString(FromHex(hex));
Console.WriteLine($"input: {input}");
Console.WriteLine($"hex: {hex}");
Console.WriteLine($"output: {output}");
Console.ReadKey();
}
public static byte[] FromHex(string hex)
{
byte[] raw = new byte[hex.Length / 2];
for (int i = 0; i < raw.Length; i++)
{
raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
return raw;
}
}
See it in action in a fiddle here:
https://dotnetfiddle.net/axUC5n
Hope this helps and good luck with your project
You should most probably use Encoding.Unicode to convert the string to a byte array: it's quite possible that some characters cannot be represented by ASCII chars.
Encoding.Unicode (UTF-16LE) always uses 2 bytes, so it's predictable: a sequence of 4 chars in the HEX string will always represent an UFT-16 CodePoint.
No matter what characters the input string contains.
Convert string to HEX:
string input = "Yourstring \"Ваша строка\"{あなたのひも},آپ کی تار";;
string hex = string.Concat(Encoding.Unicode.GetBytes(input).Select(b => b.ToString("X2")));
Convert back to string:
var bytes = new List<byte>();
for (int i = 0; i < hex.Length; i += 2) {
bytes.Add(byte.Parse(hex.Substring(i, 2), NumberStyles.HexNumber));
}
string original = Encoding.Unicode.GetString(bytes.ToArray());
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);
I'm writing little decoder. User enter string (hex) that program should decode.
My problem is that int value is not the same as inputed, therefore I don't know how should I advance after reading binary. Am I missing point on how to read binary ?
string input = "0802";
byte[] arr = Encoding.Default.GetBytes(input);
using (MemoryStream stream = new MemoryStream(arr))
{
using (BinaryReader reader = new BinaryReader(stream))
{
int a = reader.ReadInt32();
Console.WriteLine(a);
//output: 842020912
}
}
This is correct. You read 4 bytes from the string so they are interpreted as 4 bytes of your int.
If you check the hex value of your "incorrect" number 842020912 it will give you 0x32303830 and reading every byte as ASCII gives "2080".
The order is reversed as you are reading the value as little-endian.
You are doing it the hard way. I using Bytes but can modify for 1in16, or int32 very easily. :
string input = "0802";
List<byte> bytes = new List<byte>();
for (int i = 0; i < input.Length; i += 2)
{
bytes.Add(byte.Parse(input.Substring(i, 2), System.Globalization.NumberStyles.HexNumber));
}
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;
}
I have a problem about converting binary to hex then hex to binary.
For example I have an image file. First I want to convert that image to a hex string, then I want to insert this hex string to database. When a user wants to get that image file, the program has to read the hex string from the databasae, then converts to an image file.
Is it possible in C# ?
I have tried some sample methods from StackOverflow but I can't do that. I did an image file but it can't be shown.
I am waiting for your help.
Thank you
Let us know if this helps you out -
private string GetHexStringFromImage(System.Drawing.Image imageToConvert)
{
//Convert image it to byte-array
byte[] byteArray;
using (MemoryStream ms = new MemoryStream())
{
imageToConvert.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byteArray = ms.ToArray();
}
//Convert byte-array to Hex-string
StringBuilder hexBuilder = new StringBuilder();
foreach (byte b in byteArray)
{
string hexByte = b.ToString("X");
//make sure each byte is represented by 2 Hex digits
string tempString = hexByte.Length % 2 == 0 ? hexByte : hexByte.PadLeft(2, '0');
hexBuilder.Append(tempString);
}
//return Hex-string to save to DB
return hexBuilder.ToString();
}
private System.Drawing.Image GetImageFromHexString(string hexSting)
{
//Convert Hex-string from DB to byte-array
int length = hexSting.Length;
List<byte> byteList = new List<byte>();
//Take 2 Hex digits at a time
for (int i = 0; i < length; i += 2)
{
byte byteFromHex = Convert.ToByte(hexSting.Substring(i, 2), 16);
byteList.Add(byteFromHex);
}
byte[] byteArray = byteList.ToArray();
//Convert byte-array to image file and return the image
using (MemoryStream stream = new MemoryStream(byteArray))
{
return System.Drawing.Image.FromStream(stream);
}
}
You can use the JSON.NET library to serialize the byte[] into a string which will turn it into hex. Then use the same library to deserialize it back a byte[] when you need to.
I would recommend that you store it as a byte[] in the database though because it will use at least twice the space as a string (one byte in hex is 2 characters, each being a byte at minimum with ASCII or UTF8) and there is a tiny bit of overhead for the JSON format.