How to: Convert a byte Array to an int 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

How to: Convert a byte Array to an int



This example shows you how to use the BitConverter class to convert an array of bytes to an int and back to an array of bytes. You may have to convert from bytes to a built-in data type after you read bytes off the network, for example. In addition to the ToInt32(array<Byte>[]()[], Int32) method in the example, the following table lists methods in the BitConverter class that convert bytes (from an array of bytes) to other built-in types.

Type returned Method
bool ToBoolean(array<Byte>[]()[], Int32)
char ToChar(array<Byte>[]()[], Int32)
double ToDouble(array<Byte>[]()[], Int32)
short ToInt16(array<Byte>[]()[], Int32)
int ToInt32(array<Byte>[]()[], Int32)
long ToInt64(array<Byte>[]()[], Int32)
float ToSingle(array<Byte>[]()[], Int32)
ushort ToUInt16(array<Byte>[]()[], Int32)
uint ToUInt32(array<Byte>[]()[], Int32)
ulong ToUInt64(array<Byte>[]()[], Int32)

Преобразование массива байтов в значение типа "int"

В этом примере демонстрируется использование класса BitConverter для преобразования массива байтов в значение типа int и обратно в массив байтов. Например, может потребоваться преобразование из байтов во встроенный тип данных после чтения байтов из сети. В дополнение к методу ToInt32(array<Byte>[]()[], Int32), показанному в примере, для преобразования байтов (из массива байтов) в другие встроенные типы данных могут использоваться и другие методы класса BitConverter, представленные в следующей таблице.

ß--


Example

This example initializes an array of bytes, reverses the array if the computer architecture is little-endian (that is, the least significant byte is stored first), and then calls the ToInt32(array<Byte>[]()[], Int32) method to convert four bytes in the array to an int. The second argument to ToInt32(array<Byte>[]()[], Int32) specifies the start index of the array of bytes.

Note:
The output may differ depending on the endianess of your computer's architecture.
byte[] bytes = { 0, 0, 0, 25 };   // If the system architecture is little-endian (that is, little end first), // reverse the byte array. if (BitConverter.IsLittleEndian) Array.Reverse(bytes);   int i = BitConverter.ToInt32(bytes, 0); Console.WriteLine("int: {0}", i);  

 

int: 25

In this example, the GetBytes(Int32) method of the BitConverter class is called to convert an int to an array of bytes.

Note:
The output may differ depending on the endianess of your computer's architecture.
byte[] bytes = BitConverter.GetBytes(201805978); Console.WriteLine("byte array: " + BitConverter.ToString(bytes));  

 

byte array: 9A-50-07-0C

 


Пример

Этот пример инициализирует массив байтов, обращает порядок расположения элементов в массиве, если в архитектуре компьютера используется прямой порядок байтов (т. е. первым сохраняется наименее значащий байт), и затем вызывает метод ToInt32(array<Byte>[]()[], Int32) для преобразования четырех байтов массива в значение типа int. Второй аргумент ToInt32(array<Byte>[]()[], Int32) указывает начальный индекс массива байтов.

Примечание.
Результат может отличаться в зависимости от порядка следования байтов в архитектуре компьютера.
byte[] bytes = { 0, 0, 0, 25 };   // If the system architecture is little-endian (that is, little end first), // reverse the byte array. if (BitConverter.IsLittleEndian) Array.Reverse(bytes);   int i = BitConverter.ToInt32(bytes, 0); Console.WriteLine("int: {0}", i);

 

int: 25

В этом примере метод GetBytes(Int32) класса BitConverter вызывается для преобразования значения типа int в массив байтов.

Примечание.
Результат может отличаться в зависимости от порядка следования байтов в архитектуре компьютера.
byte[] bytes = BitConverter.GetBytes(201805978); Console.WriteLine("byte array: " + BitConverter.ToString(bytes));

 

byte array: 9A-50-07-0C

 



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 130; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 18.116.40.177 (0.005 с.)