// An object storing the hex value
string HexValue = "3f3300ff3f";
// An object storing the string value
string StrValue = "";
// While there's still something to convert in the hex string
while (HexValue.Length > 0)
{
// Use ToChar() to convert each ASCII value (two hex digits) to the actual character
string a = HexValue.Substring(0, 2);
uint b = System.Convert.ToUInt32(a, 16);
char c = System.Convert.ToChar(b); // ? для 255
string d = c.ToString();
StrValue += d;
// StrValue += System.Convert.ToChar(System.Convert.ToUInt32(HexValue.Substring(0, 2), 16)).ToString();
// Remove from the hex object the converted value
HexValue = HexValue.Substring(2, HexValue.Length - 2);
}
// Show what we just converted
Console.WriteLine(StrValue);
Записать 0xFF в файл
Имеется следующий код. Если я правильно понимаю, то конвертирующий hex string в ascii string. Все хорошо, пока не доходит до байта 0xff. При попытке записи в файл и последующего открытия его в шестнадцатиричном редакторе "FF" не присутствует. Из поиска стало известно, что oxff нельзя конвертировать в unicode. как эту дилемму обойти?
Текстовое представление строки в 16-ричной системе или ASCII коды строки в двоичной форме?
Код:
using System;
using System.IO;
using System.Globalization;
namespace app1
{
class Program
{
public static byte[] ParseBinary(string text) {
var data = new byte[text.Length / 2];
for(int pos = 0, i = 0; pos < text.Length; pos += 2, ++i) {
data = byte.Parse(text.Substring(pos, 2), NumberStyles.HexNumber);
}
return data;
}
public static void Main(string[] args)
{
using(var stream = new FileStream("data.dat", FileMode.Create)) {
var data = ParseBinary("FF0A3C");
stream.Write(data, 0, data.Length);
}
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
using System.IO;
using System.Globalization;
namespace app1
{
class Program
{
public static byte[] ParseBinary(string text) {
var data = new byte[text.Length / 2];
for(int pos = 0, i = 0; pos < text.Length; pos += 2, ++i) {
data = byte.Parse(text.Substring(pos, 2), NumberStyles.HexNumber);
}
return data;
}
public static void Main(string[] args)
{
using(var stream = new FileStream("data.dat", FileMode.Create)) {
var data = ParseBinary("FF0A3C");
stream.Write(data, 0, data.Length);
}
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
Спасибо большое, все верно. Все таки полезно иногда почувствовать себя клиническим идиотом))
Код:
string hexString = "FF-0A-3C";
File.WriteAllBytes("t:\\out.bin",
Array.ConvertAll(hexString.Split('-'), n => byte.Parse(n, NumberStyles.HexNumber)));
File.WriteAllBytes("t:\\out.bin",
Array.ConvertAll(hexString.Split('-'), n => byte.Parse(n, NumberStyles.HexNumber)));