Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_Prog_Guide.doc
Скачиваний:
16
Добавлен:
16.11.2019
Размер:
6.22 Mб
Скачать

Преобразование массива байтов в значение типа "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

Пример9

Этот пример инициализирует массив байтов, обращает порядок расположения элементов в массиве, если в архитектуре компьютера используется прямой порядок байтов (т. е. первым сохраняется наименее значащий байт), и затем вызывает метод 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

How to: Convert a string to an int

These examples show some different ways you can convert a string to an int. Such a conversion can be useful when obtaining numerical input from a command line argument, for example. Similar methods exist for converting strings to other numeric types, such as float or long. The table below lists some of those methods.

Numeric Type

Method

decimal

ToDecimal(String)

float

ToSingle(String)

double

ToDouble(String)

short

ToInt16(String)

long

ToInt64(String)

ushort

ToUInt16(String)

uint

ToUInt32(String)

ulong

ToUInt64(String)

Example

This example calls the ToInt32(String) method to convert the string "29" to an int. It then adds 1 to the result and prints the output.

int i = Convert.ToInt32("29");

i++;

Console.WriteLine(i);

30