logo
CSharp_Prog_Guide

Пример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