Error when convert english number to arabic number C# - c#

i need to convert my english number to arabic number to store in database
when i use this code to code
public static string ConvertNumerals(string input)
{
UTF8Encoding utf8Encoder = new UTF8Encoding();
Decoder utf8Decoder = utf8Encoder.GetDecoder();
StringBuilder convertedChars;
convertedChars = new StringBuilder();
char[] convertedChar = new char[1];
byte[] bytes = new byte[] { 217, 160 };
char[] inputCharArray = input.ToCharArray();
foreach (char c in inputCharArray)
{
if (char.IsDigit(c))
{
bytes[1] = Convert.ToByte(160 + char.GetNumericValue(c));
utf8Decoder.GetChars(bytes, 0, 2, convertedChar, 0);
convertedChars.Append(convertedChar[0]);
}
else
{
convertedChars.Append(c);
}
}
return convertedChars.ToString();
}
return string when convert it to int64 appeare this error ???

Try this method
public static string ConvertNumerals(string input)
{
char[] inputCharArray =
input.ToCharArray().Where(ch=>char.IsDigit(ch)).ToArray();
var newCharArr = new string[inputCharArray.Length];
for (int i = 0; i<inputCharArray.Length; i++)
{
var c = inputCharArray[i];
newCharArr[i] = char.GetNumericValue(c).ToString();
}
return string.Join("", newCharArr);
}

Related

C# hex to byte array loop

I have the following function:
public void SetTagData(string _data)
{
string data = _data;
byte[] ba = Encoding.Default.GetBytes(data);
string hexString = BitConverter.ToString(ba);
hexString = hexString.Replace("-", "");
var blockStart = 0;
var bufferHexBlocks = String.Empty;
try
{
for (var i = 0; i < hexString.Length; i++)
{
var byteList = new List<byte>();
byte[] datablockKey = ConvertHelpers.ConvertHexStringToByteArray(i.ToString().PadLeft(2, '0'));
var block = hexString.Substring(blockStart, 8);
byte[] datablockValue = ConvertHelpers.ConvertHexStringToByteArray(block);
byteList.AddRange(datablockKey);
byteList.AddRange(datablockValue);
_reader.Protocol("wb", byteList.ToArray());
blockStart += 8;
}
}
catch (Exception ex)
{
console.log(ex.message);
}
}
The data coming in is a bunch of hex as a string. I need to split this hex string into batches of 8 characters, append an incrementing 0 padded hex number from 00 to 1f and send this new string as a byte array to the _reader.Protocol function, which accepts a string wb as first parameter and the block as the second.
For example incoming data is:
string data = "3930313B36313B5350542D53504C3B3830303B3B352E373B3B303B303B3B3B34353036383B4E3B4E3B"
I need to send the following to the _reader.Protocol object:
(incremented padded hex 01, 02, 03, ... , 0f) and the first 8 characters of the data string, then the next, and so on as a byte array.
[013930313B], [0236313B53], etc.
I think I'm getting close... but missing something...
My problem at the moment is that I can't figure out how to loop in blocks of 8 and if the hex string is say 82 characters instead of 80 (multiple of 8), then how would I grab the last two characters without getting a IndexOutofRange exception.
Note: This is for a Windows CE application, so no new C# features please.
This below will work fine in conjunction with this answer and the sample string data given.
public static byte[] Parse(string data)
{
var count = data.Length / 8; //Might be worth throwing exception with any remainders unless you trust the source.
var needle = 0;
List<byte> result = new List<byte>(); //Inefficient but I'm being lazy
for (int i = 0; i < count; i++)
{
char[] buffer = new char[8];
data.CopyTo(needle, buffer, 0, buffer.Length);
//To get around the odd number when adding the prefixed count byte, send the hex string to the convert method separately.
var bytes = ConvertHexStringToByteArray(new string(buffer)); //Taken From https://stackoverflow.com/a/8235530/6574422
//As the count is less than 255, seems safe to parse to single byte
result.Add(byte.Parse((i + 1).ToString()));
result.AddRange(bytes);
needle += 8;
}
return result.ToArray();
}
I'm figured it out. It might not be the most efficient solution but it works just fine. I did it using a for loop inside a for loop.
In case anyone is interested here is the final code:
public void SetTagData(string _data)
{
string data = _data;
byte[] ba = Encoding.Default.GetBytes(data);
string hexString = BitConverter.ToString(ba);
hexString = hexString.Replace("-", "");
var blockStart = 0;
try
{
_reader.Protocol("s");
for(var count = 0; count < 16; count++)
{
var byteList = new List<byte>();
byte[] datablockKey = ConvertHelpers.ConvertHexStringToByteArray(count.ToString("X2"));
byteList.AddRange(datablockKey);
for (var innerCount = 0; innerCount < 4; innerCount++)
{
var block = String.Empty;
if (!String.IsNullOrEmpty(hexString.Substring(blockStart, 2)))
{
block = hexString.Substring(blockStart, 2);
}
else
{
block = "20";
}
byte[] datablockValue = ConvertHelpers.ConvertHexStringToByteArray(block);
byteList.AddRange(datablockValue);
blockStart += 2;
}
_reader.Protocol("wb", byteList.ToArray());
}
}
catch (Exception)
{
}
}

C/C# Marshal.PtrToStringAnsi Chinese garbled

a.
static void onMessage(IntPtr str)
{
string message = Marshal.PtrToStringAnsi(str);
Console.Write(message);
}
, its Return Chinese garbled。
b.
public static void onMessage(IntPtr str)
{
int nAnsiLength = Marshal.PtrToStringAnsi(str).Length;
int nUniLength = Marshal.PtrToStringUni(str).Length;
int nMaxLength = (nAnsiLength > nUniLength) ? nAnsiLength : nUniLength;
int length = 0;//循环查找字符串的长度
for (int i = 0; i < nAnsiLength; i++)
{
byte[] strbuf1 = new byte[1];
Marshal.Copy(str + i, strbuf1, 0, 1);
if (strbuf1[0] == 0)
{
break;
}
length++;
}
byte[] strbuf = new byte[length];
Marshal.Copy(str, strbuf, 0, length);
string message = System.Text.UTF8Encoding.UTF8.GetString(strbuf);
}
, Chinese display, but the length of the string returned。
I need help!
Here there are various codepages that are chinese... Try the one that seems to fit what you expect. I've even simplified the code to copy the IntPtr buffer to a byte[] buffer.
public static void onMessage(IntPtr str) {
int length = 0;//循环查找字符串的长度
while (Marshal.ReadByte(str + length) != 0) {
length++;
}
byte[] strbuf = new byte[length];
Marshal.Copy(str, strbuf, 0, length);
// Taken from https://msdn.microsoft.com/it-it/library/system.text.encodinginfo.getencoding(v=vs.110).aspx
string message1 = Encoding.UTF8.GetString(strbuf);
string message2 = Encoding.GetEncoding(54936).GetString(strbuf);
string message3 = Encoding.GetEncoding(936).GetString(strbuf);
string message4 = Encoding.GetEncoding(950).GetString(strbuf);
string message5 = Encoding.GetEncoding(10002).GetString(strbuf);
string message6 = Encoding.GetEncoding(10008).GetString(strbuf);
string message7 = Encoding.GetEncoding(20000).GetString(strbuf);
string message8 = Encoding.GetEncoding(20002).GetString(strbuf);
string message9 = Encoding.GetEncoding(20936).GetString(strbuf);
string message10 = Encoding.GetEncoding(50227).GetString(strbuf);
string message11 = Encoding.GetEncoding(51936).GetString(strbuf);
string message12 = Encoding.GetEncoding(52936).GetString(strbuf);
}

C# reading a byte array as a string

I am coding in c#.
I need to read the string of bytes without converting.
bytes: 68
string: 44
I want to be able to convert it through code
I figured it out
#region "Grab Bytes Function"
private string grabBytes(byte[] buffer)
{
byte[] bytes = buffer;
string output = string.Empty;
foreach (byte item in bytes)
{
output += Convert.ToString(item, 16).ToUpper().PadLeft(2, '0');
}
return output;
}
#endregion
#region "Grab String Function"
private string grabString(byte[] buffer)
{
byte[] bytes = buffer;
string output = string.Empty;
foreach (byte item in bytes)
{
for (int i = 0; i < 255; i++)
{
if (grabBytes(new byte[] { item }) == grabBytes(new byte[] { byte.Parse(i.ToString()) }))
output += item + ".";
}
}
string output1 = output.Remove(output.Count() - 1, 1);
if (output1 != "0.0.0.0")
return output1;
else
return "";
}
#endregion
Your code is equivalent to this one:
private string grabString(byte[] buffer)
{
var asDecimal = string.Join(".", buffer));
return (asDecimal == "0.0.0.0" ? "" : asDecimal);
}

HTML hex to polish characters

I'm downloading HTML file with polish characters, and parsing it to string by:
public static string HexToString(string hex)
{
var sb = new StringBuilder();
for (int i = 0; i < hex.Length; i += 2)
{
string hexdec = hex.Substring(i, 2);
int number = int.Parse(hexdec, NumberStyles.HexNumber);
char charToAdd = (char)number;
sb.Append(charToAdd);
}
return sb.ToString();
}
so when I found %21 I'm sending 21 to HexToString() and in return there is !, this is ok, but char ą is represented as %C4%85 (Ä) and I whant to get ą char
The problem here is that you are treating the hex codes as if they are UTF16 (which is the native format for char), but they are in fact UTF8.
This is easy to resolve using a UTF8 encoding.
First, let's write a handy StringToByteArray() method:
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();
}
Now you can convert the hex string to text like so:
string hexStr = "C485"; // Or whatever your input hex string is.
var bytes = StringToByteArray(hexStr);
string text = Encoding.UTF8.GetString(bytes);
// ...use text
Matthew is right, but you can also use this:
public static string ConvertHexToString(string HexValue)
{
var res = "";
var replacedHex = HexValue.Replace("%", String.Empty);
while (replacedHex.Length > 0)
{
res += System.Convert.ToChar(System.Convert.ToUInt32(replacedHex.Substring(0, 2), 16)).ToString();
replacedHex = replacedHex.Substring(2, replacedHex.Length - 2);
}
return res;
}

Binary to Text Translation C# [duplicate]

Hi i was able to convert a ASCII string to binary using a binarywriter .. as 10101011 . im required back to convert Binary ---> ASCII string .. any idea how to do it ?
This should do the trick... or at least get you started...
public Byte[] GetBytesFromBinaryString(String binary)
{
var list = new List<Byte>();
for (int i = 0; i < binary.Length; i += 8)
{
String t = binary.Substring(i, 8);
list.Add(Convert.ToByte(t, 2));
}
return list.ToArray();
}
Once the binary string has been converted to a byte array, finish off with
Encoding.ASCII.GetString(data);
So...
var data = GetBytesFromBinaryString("010000010100001001000011");
var text = Encoding.ASCII.GetString(data);
If you have ASCII charters only you could use Encoding.ASCII.GetBytes and Encoding.ASCII.GetString.
var text = "Test";
var bytes = Encoding.ASCII.GetBytes(text);
var newText = Encoding.ASCII.GetString(bytes);
Here is complete code for your answer
FileStream iFile = new FileStream(#"c:\test\binary.dat",
FileMode.Open);
long lengthInBytes = iFile.Length;
BinaryReader bin = new BinaryReader(aFile);
byte[] byteArray = bin.ReadBytes((int)lengthInBytes);
System.Text.Encoding encEncoder = System.Text.ASCIIEncoding.ASCII;
string str = encEncoder.GetString(byteArray);
Take this as a simple example:
public void ByteToString()
{
Byte[] arrByte = { 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 };
string x = Convert.ToBase64String(arrByte);
}
This linked answer has interesting details about this kind of conversion:
binary file to string
Sometimes instead of using the built in tools it's better to use "custom" code.. try this function:
public string BinaryToString(string binary)
{
if (string.IsNullOrEmpty(binary))
throw new ArgumentNullException("binary");
if ((binary.Length % 8) != 0)
throw new ArgumentException("Binary string invalid (must divide by 8)", "binary");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < binary.Length; i += 8)
{
string section = binary.Substring(i, 8);
int ascii = 0;
try
{
ascii = Convert.ToInt32(section, 2);
}
catch
{
throw new ArgumentException("Binary string contains invalid section: " + section, "binary");
}
builder.Append((char)ascii);
}
return builder.ToString();
}
Tested with 010000010100001001000011 it returned ABC using the "raw" ASCII values.

Categories