C# User Input Into Byte Array - c#

This is probably a very ridiculous question but I can't figure out how to import the user's input into a byte array. Since user input is always in a string format a conversation will be needed, however the numbers he entered must be the same in the array. For example:
Console.Write("Enter a number: ");
string text = Console.ReadLine();
/* Lets assume the user entered 22, 101, 1
How would I get those exact numbers in byte[]
*/
byte[] arr = new Byte[] {text};
UPDATED: what I am looking to get is
byte[] arr = new Byte[] {22, 101, 1};

Console.Write("Enter a number: ");
string text = Console.ReadLine();
byte[] byteArrayUTF= System.Text.Encoding.UTF8.GetBytes (text);
byte[] byteArrayASCII= System.Text.Encoding.ASCII.GetBytes (text);
You can find a better explanation here for the difference between UTF8 and ASCII
Unicode is a superset of ASCII, and the numbers 0–128 have the same
meaning in ASCII as they have in Unicode.
(From the updates)I think You are actually looking for converting the input string (comma separated values ) into an array of bytes. if so you can use thm Like the following:
string text = Console.ReadLine();
byte[] byteArr = text.Split(',').Select(x => Convert.ToByte(x)).ToArray();

This uses LINQ-to-Objects to "pipeline" from a string to an array of strings to a sequence of bytes to an array of bytes:
var arr = text
.Split(',')
.Select(digits => Byte.Parse(digits))
.ToArray();

While the other answers explain how to convert a string to a byte[],
I believe what you really want is to get the numbers into a byte[]
var input = "22, 101, 1";
var numbers = input.Split(',')
.Select(p => byte.Parse(p));
This will split the input at every , and convert each part to an integer.

You can use the GetBytes function to convert strings into bytes.
byte[] arr = Encoding.ASCII.GetBytes(text)
byte[] arr = System.Text.UTF8Encoding.UTF8.GetBytes(text)
byte[] arr = Encoding.Unicode.GetBytes(text)
If you are looking for a specific encoding type you can use the following to convert from other standard encoding types into what .NET provides.
byte[] arr = GetStringEncoding(StringEncodingType.CHARSET_UTF_16BE_CODEPAGE).GetBytes(text);
public static Encoding GetStringEncoding(StringEncodingType type)
{
switch (type)
{
case StringEncodingType.ASCII:
return Encoding.ASCII;
case StringEncodingType.Unicode:
return Encoding.Unicode;
//return Encoding.UTF7;
case StringEncodingType.UTF8:
return Encoding.UTF8;
//case StringEncodingType.CHARSET_UTF_16LE_CODEPAGE:// 1200, same as unicode
case StringEncodingType.CHARSET_UTF_16BE_CODEPAGE:// 1201,
case StringEncodingType.CHARSET_UTF_32LE_CODEPAGE:// 12000,
case StringEncodingType.CHARSET_UTF_32BE_CODEPAGE:// 12001,
case StringEncodingType.CHARSET_WINDOWS_1251_CODEPAGE:// 1251,
case StringEncodingType.CHARSET_WINDOWS_1252_CODEPAGE:// 1252,
case StringEncodingType.CHARSET_WINDOWS_1253_CODEPAGE:// 1253,
case StringEncodingType.CHARSET_WINDOWS_1255_CODEPAGE:// 1255,
case StringEncodingType.CHARSET_ISO_2022_JP_CODEPAGE:// 50220,
case StringEncodingType.CHARSET_ISO_2022_CN_CODEPAGE:// 50227,
case StringEncodingType.CHARSET_ISO_2022_KR_CODEPAGE:// 50225,
case StringEncodingType.CHARSET_ISO_8859_5_CODEPAGE:// 28595,
case StringEncodingType.CHARSET_ISO_8859_7_CODEPAGE:// 28597,
case StringEncodingType.CHARSET_ISO_8859_8_CODEPAGE:// 28598,
case StringEncodingType.CHARSET_BIG5_CODEPAGE:// 950,
case StringEncodingType.CHARSET_GB18030_CODEPAGE:// 54936,
case StringEncodingType.CHARSET_EUC_JP_CODEPAGE:// 20932,
case StringEncodingType.CHARSET_EUC_KR_CODEPAGE:// 51949,
case StringEncodingType.CHARSET_SHIFT_JIS_CODEPAGE:// 932,
case StringEncodingType.CHARSET_IBM855_CODEPAGE:// 855,
case StringEncodingType.CHARSET_IBM866_CODEPAGE:// 866,
case StringEncodingType.CHARSET_KOI8_R_CODEPAGE:// 20866,
case StringEncodingType.CHARSET_MACCYRILLIC_CODEPAGE:// 10007,
case StringEncodingType.CHARSET_HZ_GB_2312_CODEPAGE:// 52936,
//case StringEncodingType.CHARSET_X_ISO_10646_UCS_4_3412_CODEPAGE:// 12000, same as CHARSET_UTF_32LE_CODEPAGE
//case StringEncodingType.CHARSET_X_ISO_10646_UCS_4_2143_CODEPAGE:// 12000, same as CHARSET_UTF_32LE_CODEPAGE
case StringEncodingType.CHARSET_WINDOWS_874_CODEPAGE:// 874
return Encoding.GetEncoding((int)type);
default:
throw new System.NotSupportedException("Error Missing String Encoding Type:" + type.ToString());
}
}
public enum StringEncodingType // the numbers are the codepage
{
Unknown = -1,
ASCII = 20127,
Unicode = 1200,
UTF8 = 65001,
//CHARSET_UTF_16LE_CODEPAGE = 1200, same as unicode
CHARSET_UTF_16BE_CODEPAGE = 1201,
CHARSET_UTF_32LE_CODEPAGE = 12000,
CHARSET_UTF_32BE_CODEPAGE = 12001,
CHARSET_WINDOWS_1251_CODEPAGE = 1251,
CHARSET_WINDOWS_1252_CODEPAGE = 1252,
CHARSET_WINDOWS_1253_CODEPAGE = 1253,
CHARSET_WINDOWS_1255_CODEPAGE = 1255,
CHARSET_ISO_2022_JP_CODEPAGE = 50220,
CHARSET_ISO_2022_CN_CODEPAGE = 50227,
CHARSET_ISO_2022_KR_CODEPAGE = 50225,
CHARSET_ISO_8859_5_CODEPAGE = 28595,
CHARSET_ISO_8859_7_CODEPAGE = 28597,
CHARSET_ISO_8859_8_CODEPAGE = 28598,
CHARSET_BIG5_CODEPAGE = 950,
CHARSET_GB18030_CODEPAGE = 54936,
CHARSET_EUC_JP_CODEPAGE = 20932,
CHARSET_EUC_KR_CODEPAGE = 51949,
CHARSET_SHIFT_JIS_CODEPAGE = 932,
CHARSET_IBM855_CODEPAGE = 855,
CHARSET_IBM866_CODEPAGE = 866,
CHARSET_KOI8_R_CODEPAGE = 20866,
CHARSET_MACCYRILLIC_CODEPAGE = 10007,
CHARSET_HZ_GB_2312_CODEPAGE = 52936,
//CHARSET_X_ISO_10646_UCS_4_3412_CODEPAGE = 12000, same as CHARSET_UTF_32LE_CODEPAGE
//CHARSET_X_ISO_10646_UCS_4_2143_CODEPAGE = 12000, same as CHARSET_UTF_32LE_CODEPAGE
CHARSET_WINDOWS_874_CODEPAGE = 874
}

Related

byte[] with ASCII values to string to int

So someone took int value, converted it to string then converted it to ASCII values and then finally to byte[] with inconsistent length 1 - 4 bytes.
e.g. 100 -> "100" -> { 49, 48, 48 }.
Now I need that int value and I did it like this:
{ 49, 48, 48 } -> '1' + '0' + '0' -> "100" -> 100
switch (header[25].Count)
{
case 1:
hex = "" + (char)header[25][0];
amountOfData = Convert.ToInt32(hex, 16);
break;
case 2:
hex = "" + (char)header[25][0] + (char)header[25][1];
amountOfData = Convert.ToInt32(hex, 16);
break;
case 3:
hex = "" + (char)header[25][0] + (char)header[25][1] + (char)header[25][2];
amountOfData = Convert.ToInt32(hex, 16);
break;
case 4:
hex = "" + (char)header[25][0] + (char)header[25][1] + (char)header[25][2] + (char)header[25][3];
amountOfData = Convert.ToInt32(hex, 16); ;
break;
default:
break;
}
but maybe there is better solution...
EDIT: sorry for not mentioning that, but header is List<List<byte>>
You can use the Encoding/GetString method to convert bytes of different encodings (e.g. ASCII in your case) to a .NET string:
var input = new byte[] { 49, 48, 48 };
var str = Encoding.ASCII.GetString(input);
var result = int.Parse(str, NumberStyles.None, CultureInfo.InvariantCulture);
You can use library functions to parse from byte-like data to primitives; you're talking about ASCII, which means that Utf8Parser will work fine for us (all ASCII is also valid UTF8, although the reverse is obviously not true); normally, we would expect that header[25] is a byte[], a segment there-of, or some other raw binary source, but: ultimately, something like:
var span = new ReadOnlySpan<byte>(header[25], 0, header[25].Count);
if (!Utf8Parser.TryParse(span, out int amountOfData, out _))
ThrowSomeError(); // not an integer
If header[25] is something less convenient (like a List<byte> - I notice that in your example, your header[25] has a .Count not a .Length, which suggests it isn't a byte[]), then you can always either stackalloc a local buffer and copy the data out, or you can peek inside the list with CollectionMarshal.AsSpan<T>(List<T>), which returns a Span<T> from the underlying data:
var span = CollectionMarshal.AsSpan(header[25]);
if (!Utf8Parser.TryParse(span, out int amountOfData, out _))
ThrowSomeError(); // not an integer
As a runnable example that just shows the API:
using System;
using System.Buffers.Text;
Span<byte> span = stackalloc byte[] { 49, 48, 48 };
if (!Utf8Parser.TryParse(span, out int amountOfData, out _))
throw new FormatException();
Console.WriteLine(amountOfData); // 100

Kotlin equivalent of C# BitConverter.ToString

It's BitConverter.ToString(blabla) same with blabla.toString?
Example:
int values = 1500;
byte[] bytes = BitConverter.GetBytes(values);
byte[] bits = new byte[2];
bits.SetValue(bytes[0], 0);
bits.SetValue(bytes[1], 1);
string hex = BitConverter.ToString(bits);
string hexHub1 = hex.Substring(0, hex.IndexOf("-"));
string hexHub2 = hex.Substring(hex.IndexOf("-") +1,2);
And get "DC-05"
How can i implement anything like this in kotlin?
byteArray.toString() is used to convert ByteArray to String. On the other hand, contentToString() will result elements in the array.
val byteArray = "Hello".toByteArray(Charsets.UTF_8)
println(byteArray.contentToString()) // this will print numbers
println(byteArray.toString(Charsets.UTF_8))

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 byte array to binary values and then write it in a comma separated text file

I have a byte array:
newMsg.DATA = new byte[64];
How can I convert it into binary value and then write it in text file with comma separation. Comma should be in between binary values not bytes.....
like 1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,0.......
Here is an example that uses LINQ:
byte[] arr = new byte[] { 11, 55, 255, 188, 99, 22, 31, 43, 25, 122 };
string[] result = arr.Select(x => string.Join(",", Convert.ToString(x, 2)
.PadLeft(8, '0').ToCharArray())).ToArray();
System.IO.File.WriteAllLines(#"D:\myFile.txt", result);
Every number in byte[] arr is converted to a binary number with Convert.ToString(x, 2) and the comma "," is added between binary values with string.Join(",",...). At the end you can write all the elements in result to a text file by using System.IO.File.WriteAllLines.
The example above gives you this kind of output in a txt file:
0,0,0,0,1,0,1,1
0,0,1,1,0,1,1,1
1,1,1,1,1,1,1,1
...
Explanation of Convert.ToString(value, baseValue):
The first parameter value represents the number you want to convert to a string
and the second parameter baseValue represents which type of conversion you want to perform.
Posible baseValues are : 2,8,10 and 16.
BaseValue = 2 - represents a conversion to a binary number representation.
BaseValue = 8 - represents a conversion to a octal number representation.
BaseValue = 10 - represents a conversion to a decimal number representation.
BaseValue = 16 - represents a conversion to a hexadecimal number representation.
I think this will Help you c# provides inbuilt functionality to do so
with help of Convert.ToString(byte[],base); here base could be[2(binary),8(octal),16(HexaDecimal)]
byte[] data = new byte[64];
// 2nd parameter 2 is Base e.g.(binary)
string a = Convert.ToString(data[data.Length], 2);
StringBuilder sb = new StringBuilder();
foreach(char ch in a.ToCharArray())
{
sb.Append(ch+",");
}
// This is to remove last extra ,
string ans = sb.ToString().Remove(sb.Length - 1, 1);
This should get you going:
var bytes = new byte[] { 128, 255, 2 };
var stringBuilder = new StringBuilder();
for (var index = 0; index < bytes.Length; index++)
{
var binary = Convert.ToString(bytes[index], 2).PadLeft(8, '0');
var str = string.Join(",", binary.ToCharArray());
stringBuilder.Append(str);
if (index != bytes.Length -1) stringBuilder.Append(",");
}
Console.WriteLine(stringBuilder);

save string array in binary format

string value1 , value1 ;
int length1 , length2 ;
System.Collections.BitArray bitValue1 = new System.Collections.BitArray(Length1);
System.Collections.BitArray bitValue2 = new System.Collections.BitArray(Length2);
I'm looking for the fastest way to covert each string to BitArray with defined length for each string (the string should be trimmed if it is larger than defined length and if strings size is smaller remaining bits will be filled with false) and then put this two strings together and write it in a binary file .
Edit :
#dtb : a simple example can be like this value1 = "A" ,value2 = "B" and length1 =8 and length2 = 16 and the result will be 010000010000000001000010
the first 8 bits are from "A" and next 16 bits from "B"
//Source string
string value1 = "t";
//Length in bits
int length1 = 2;
//Convert the text to an array of ASCII bytes
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(value1);
//Create a temp BitArray from the bytes
System.Collections.BitArray tempBits = new System.Collections.BitArray(bytes);
//Create the output BitArray setting the maximum length
System.Collections.BitArray bitValue1 = new System.Collections.BitArray(length1);
//Loop through the temp array
for(int i=0;i<tempBits.Length;i++)
{
//If we're outside of the range of the output array exit
if (i >= length1) break;
//Otherwise copy the value from the temp to the output
bitValue1.Set(i, tempBits.Get(i));
}
And I'm going to keep saying it, this assumes ASCII characters so anything above ASCII 127 (such as the é in résumé) will freak out and probably return ASCII 63 which is the question mark.
When converting a string to something else you need to consider what encoding you want to use. Here's a version that uses UTF-8
bitValue1 = System.Text.Encoding.UTF8.GetBytes(value1, 0, length1);
Edit
Hmm... saw that you're looking for a BitArray and not a ByteArray, this won't help you probably.
Since this is not a very clear question I'll give this a shot nonetheless,
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public static void RunSnippet()
{
string s = "123";
byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(s);
System.Collections.BitArray bArr = new System.Collections.BitArray(b);
Console.WriteLine("bArr.Count = {0}", bArr.Count);
for(int i = 0; i < bArr.Count; i++)
Console.WriteLin(string.Format("{0}", bArr.Get(i).ToString()));
BinaryFormatter bf = new BinaryFormatter();
using (FileStream fStream = new FileStream("test.bin", System.IO.FileMode.CreateNew)){
bf.Serialize(fStream, (System.Collections.BitArray)bArr);
Console.WriteLine("Serialized to test.bin");
}
Console.ReadLine();
}
Is that what you are trying to achieve?
Hope this helps,
Best regards,
Tom.

Categories