logo search
CSharp_Prog_Guide

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

В этом примере демонстрируется использование класса 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