C#: преобразовать строку в массив байтов
Есть строка «612345» . HEX-editor преобразует ее в следующий массив: <36 31 32 33 34 35 36>. Я хочу добавить эти значения (т.е. 36,31. 36) в массив байтов:
только не хардкорно, а программно.
Я добился того, что в строке уже есть HEX-значения: «36 31 32 33 34 35 36» теперь надо как-то добавить перед каждым «0х» и добавить в массив. Подскажите, как это сделать!
Так должно сработать:
Судя по значениям, тебе подойдёт ASCIIEncoding (учти, что не все символы в ней представимы) и UTF8Encoding. Учти, что .NET использует UnicodeEncoding (она же UTF16) для хранения строк, и любые преобразования не всегда однозначны, хотя well-formed строку в UTF16 можно привести в UTF8 и наоборот. Про ASCII даже такое утверждение неверно.
https://msdn.microsoft.com/en-us/library/system.text.asciiencoding(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.text.utf8encoding(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.text.unicodeencoding(v=vs.110).aspx
Если ты хочешь получить генерацию кода, просто примени к массиву байт Select с приведением в 16ричную систему счисления в нужном виде и String.Join для объединения в строку.
Преобразование строки в массив байт:
самый простой способ
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.6.15.43493
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
C# String to Byte Array
In C# programming, we can easily convert the string into the byte array with the help of different methods. As we know, in C# programming, each string’s character is stored using two bytes. But the ASCII character is stored using one byte. So, we may lose some data during conversion from string to byte array. But by using some methods, we can easily convert the C# string into byte array. In this guide, we will show you different examples of how to convert the string into the byte array using different methods.
Methods to Convert the String to the Byte Array in C# Programming:
Here, we have two methods to convert the string to byte array:
GetByte() method: By using this method, we are converting our string data into byte array data in this guide.
Syntax:
ToByte() method: We can covert our string type data into byte array type data using this ToByte() method. Also, we use this method in this guide.
Syntax:
Now, we will explain both methods with the help of examples in C# in Ubuntu 20.04 so that it is easy to understand this concept. Have a look at the examples, which are given below:
Example # 1: Using GetBytes() Method in C# Program in Ubuntu 20.04
We have an example in which we are using the GetByte() method to convert our string data into byte array in C# programming. We are performing the given examples in Ubuntu 20.04. First, we have to create a file in Ubuntu 20.04 text editor with a filename having an extension of “.cs”. Then, write the given code in this file of Ubuntu 20.04 and save it. You may use any text editor of your choice on which you want to run your program.
In the first line of this code, we have “using System”, a library for accessing functions and methods in C# programming. Any method and function required in this code can be accessed using this “using System” library. In the next line, we are using “System.Text”. The “System.Text” is a namespace containing different classes. These classes represent ASCII and Unicode char encodings.
It may contain an abstract class and also a helper class. Now, we are declaring a class with the name “StrToByte” in this code. After this class, we invoked a “main” function which is static here. The “static void Main(String[] args)” is the main method of this C# program. The command line values are in this “string[ ] args”. It is a variable. We can also use only “string[ ]” in our code, but for our ease, we use “args” with it. We declare and initialize a variable named “data” with “string” data type and assigning string data to this variable which is “My First String Program”.
Now, we will convert our string data to Byte Array using the GetByte() method. We have “byte[ ] byteArray = Encoding.ASCII.GetBytes(data)”. In this statement, we have a byte array with the name “byteArray” and invoke a method of GetByte() here. It gets the string data and then converts this string data into bytes and stores it in this byte array. Next, we have “Console.WriteLine” which we use when we want to display something on the screen. Here, we are displaying a line using this “Console.WriteLine”. We are using the “foreach” loop, which gets the “bytes” present in “byteArray” and prints these Bytes Array by using “Console.WriteLine”.
Now, for displaying the result of the previous code, we run two commands on the terminal of Ubuntu 20.04. One is the “MCS” command having a filename with the extension of “.cs”. It is a compiler that compiles our C# code, and then, for execution, we have a “mono” command with the same filename. But this time, we use the “.exe” file extension. The output of this code is found in the following image:
Here, you see that it prints the line, then converts all the characters present in the given string into their byte codes with the help of the GetByte() method, and displays each character byte code in a separate line.
Example # 2: Using ToBytes() Method in C# Program
We have another example in which we are using the second method that is “ToGet()” method. It works the same as the “GetByte()” method. Let’s see how we convert the string into a byte array with the help of the “ToGet()” method in the following C# program:
In this code, we use the “using System” statement for getting the methods and functions of this code. Then, we have a namespace “using System.text”, which we discussed in detail in the previous code. We have a public class here with the name “ArrayByte”. Inside this class, we invoked a function. This is the “Main” function of our C# program. Then, we declare a string named “str” and store string data in this string variable “str”. After that, we create a byte array of the same string length stored in “string str”.
The name of this byte array is “byt”, which is used to store the byte data of the given string in it. Now, we are using the “for” loop here, so that it will get all the string characters and convert them into bytes and store them in it. This loop executes until “b” is less than “str.Length”. The value of “b” will increment each time the loop executes and convert each character into bytes with the help of the “Convert.ToByte(str[b])” statement. Plus, it stores these byte values in the “byt[b]” array. When it converts all the string characters and stores them in a byte array, it comes out from this “for” loop and moves to the next statement when the condition becomes false.
After this “for” loop, we have another “for” loop, which is used to print all the bytes of the characters. This “for” loop is the same as the previous for “loop”, but this time, we are printing the bytes array with the help of “Console.WriteLine”. The “Console.WriteLine” first prints the line “Byte of char” and then gets the character from the string by using “str[b]”. After this, it will display the byte code of this character which is stored in the bytes array with the help of “byt[b]”. Now, you can easily understand the last line of code. The output of this code is shown in the following image. See how this code works and provides the output.
This output shows that it takes all the characters and the spaces in the string and converts them into the bytes. You see, it also converts the space in its byte code. It displays all the characters with their byte codes in a separate line.
Conclusion:
This guide teaches the string to byte array conversion in C# programming in Ubuntu 20.04. We try our best to explain all the concepts and methods used in these codes of the C# program in detail so that you can easily get the point of how to convert the string into a byte array using “GetByte()” and “ToByte()” methods. We demonstrate two examples in this guide that provide a better understanding of this concept. In this conversion, you may lose some data if you are using those characters not in ASCII code. We hope you found this article helpful. Check the other Linux Hint articles for more tips and tutorials.
Как преобразовать строку в массив байт c
Лучший отвечающий
Вопрос
i am trying to convert string to byte using this code, but it gives error pls help me..
public static byte [] StringToByte( string InString) <
ByteStrings = InString.Split(" ".ToCharArray());
ByteOut = new byte [ByteStrings.Length-1];
for ( int i = 0;i==ByteStrings.Length-1;i++) <
ByteOut = Convert.ToByte(("0x" + ByteStrings));
Ответы
The easiest way to convert a string into a byte array is to use the GetBytes() method of an instantiated text encoding class, consider this example:
System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
Byte[] bytes = Encoding.GetBytes(yourString);
- Предложено в качестве ответа Wanaco 8 июня 2010 г. 22:39
- Изменено OmegaMan 1 августа 2012 г. 16:47 Changed encoding (#Fail) to Encoding
- Помечено в качестве ответа Kareninstructor MVP 20 сентября 2019 г. 12:34
Все ответы
The easiest way to convert a string into a byte array is to use the GetBytes() method of an instantiated text encoding class, consider this example:
System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
Byte[] bytes = Encoding.GetBytes(yourString);
- Предложено в качестве ответа Wanaco 8 июня 2010 г. 22:39
- Изменено OmegaMan 1 августа 2012 г. 16:47 Changed encoding (#Fail) to Encoding
- Помечено в качестве ответа Kareninstructor MVP 20 сентября 2019 г. 12:34
public static byte [] ToByteArray( string StringToConvert)
char [] CharArray = StringToConvert.ToCharArray();
byte [] ByteArray = new byte [CharArray.Length];
for ( int i = 0; i < CharArray.Length; i++)
ByteArray = Convert .ToByte(CharArray);
Could you give us an example of what your input string looks like? In the meantime here are couple areas you may want to check.
When you create ByteOut I notice that you are creating to the Length — 1 of the initial ByteStrings. If I’m understanding your code correctly it looks as if you want to take each character from the InString and convert that to a byte. In that’s the case then this will be a 1-to-1 conversion so you’ll need to intialize ByteStrings to be the length of InString. Consider what would happen if you had an InString of 1. ByteString would be intialized to 0 (Length — 1) meaning that when you tried to assign a value to ByteString at the end of the for loop you would recieve an IndexOutOfRangeException.
Next, Convert.ToByte(. ) returns a single byte but your code is currently attempting to assign that to an array as follows:
ByteOut = Convert.ToByte(("0x" + ByteStrings)); // where ByteOut is an array.
You will need to actually assign the resultse of Convert.ToByte(. ) to an individual element of the array as follows:
ByteOut = Convert.ToByte(("0x" + ByteStrings)); // where ‘i’ is the iterator of the for loop.
I suspect that you will also need to massage the string further to get it in a for suitable for a byte as well, but we can cross that bridge later (I want to make sure i understand your intentions correctly before i make any suggestions).
Как преобразовать строку в массив байтов?
Я еще не нашел решения для этого, и у меня голова болит. D:
Теперь скажем, у меня есть строка как:
Я хочу преобразовать это в массив байтов.
Как лучше всего это сделать?
Ответы (3)
Вот альтернативный метод, использующий char[] как IEnumerable<char> :
А также, если строка может быть неправильно отформатирована, используйте это (это то же самое, за исключением формата TryX ):
Если вы определите метод расширения для разделения вашей последовательности на подпоследовательности заданного размера, например Handcraftsman’s InSetsOf , вы можете сделать это как однострочный: