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

Преобразование шестнадцатеричных строк10

В следующих примерах показано, как выполнить преобразование в шестнадцатеричные строки и наоборот. Первый пример демонстрирует, как получить шестнадцатеричное значение каждого символа в строке. Второй пример выполняет разбор строки шестнадцатеричных значений и выводит символ, соответствующий каждому шестнадцатеричному значению. Третий пример демонстрирует альтернативный способ разбора значения шестнадцатеричной строки до целого числа.

Пример

Результатом следующего примера является шестнадцатеричное значение каждого символа в string. Сначала выполняется разбор string до массива символов. Затем для каждого символа вызывается метод ToInt32(Char) для получения его числового значения. В конце, число представляется шестнадцатеричном виде.

--

This example parses a string of hexadecimal values and outputs the character corresponding to each hexadecimal value. First it calls the Split(array<Char>[]()[]) method to obtain each hexadecimal value as an individual string in an array. Then it calls ToInt32(String, Int32) to convert the hexadecimal value to a decimal value represented as an int. It shows two different ways to obtain the character corresponding to that character code. The first technique uses ConvertFromUtf32(Int32) which returns the character corresponding to the integer argument as a string. The second technique explicitly casts the int to a char.

string hexValues = "48 65 6C 6C 6F 20 57 6F 72 6C 64 21";

string[] hexValuesSplit = hexValues.Split(' ');

foreach (String hex in hexValuesSplit)

{

// Convert the number expressed in base-16 to an integer.

int value = Convert.ToInt32(hex, 16);

// Get the character corresponding to the integral value.

string stringValue = Char.ConvertFromUtf32(value);

char charValue = (char)value;

Console.WriteLine("hexadecimal value = {0}, int value = {1}, char value = {2} or {3}", hex, value, stringValue, charValue);

}

hexadecimal value = 48, int value = 72, char value = H or H

hexadecimal value = 65, int value = 101, char value = e or e

hexadecimal value = 6C, int value = 108, char value = l or l

hexadecimal value = 6C, int value = 108, char value = l or l

hexadecimal value = 6F, int value = 111, char value = o or o

hexadecimal value = 20, int value = 32, char value = or

hexadecimal value = 57, int value = 87, char value = W or W

hexadecimal value = 6F, int value = 111, char value = o or o

hexadecimal value = 72, int value = 114, char value = r or r

hexadecimal value = 6C, int value = 108, char value = l or l

hexadecimal value = 64, int value = 100, char value = d or d

hexadecimal value = 21, int value = 33, char value = ! or !

This example shows you another way to convert a hexadecimal string to an integer, by calling the Parse(String, NumberStyles) method.

string hexString = "8E2";

int num = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber);

Console.WriteLine(num);

2274

Этот пример выполняет разбор string шестнадцатеричных значений и выводит символ, соответствующий каждому шестнадцатеричному значению. Сначала вызывается метод Split(array<Char>[]()[]) для получения каждого шестнадцатеричного значения как отдельной string в массиве. Затем вызывается метод ToInt32(String, Int32) для преобразования шестнадцатеричного значения в десятичное, представленное в формате int. В примере показано два разных способа получения символа, соответствующего этому коду символа. В первом случае используется ConvertFromUtf32(Int32), возвращающий символ, который соответствует целочисленному аргументу в виде string. По второму способу выполняется явное приведение int к char.

--

В следующем примере показан еще один способ преобразования шестнадцатеричной string в целое число путем вызова метода Parse(String, NumberStyles).

--

Arrays

An array is a data structure that contains several variables of the same type. Arrays are declared with a type:

type[] arrayName;

The following examples create single-dimensional, multidimensional, and jagged arrays:

class TestArraysClass

{

static void Main()

{

// Declare a single-dimensional array

int[] array1 = new int[5];

// Declare and set array element values

int[] array2 = new int[] { 1, 3, 5, 7, 9 };

// Alternative syntax

int[] array3 = { 1, 2, 3, 4, 5, 6 };

// Declare a two dimensional array

int[,] multiDimensionalArray1 = new int[2, 3];

// Declare and set array element values

int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } };

// Declare a jagged array

int[][] jaggedArray = new int[6][];

// Set the values of the first array in the jagged array structure

jaggedArray[0] = new int[4] { 1, 2, 3, 4 };

}

}

Array Overview

An array has the following properties:

  • An array can be Single-Dimensional, Multidimensional or Jagged.

  • The default value of numeric array elements are set to zero, and reference elements are set to null.

  • A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.

  • Arrays are zero indexed: an array with n elements is indexed from 0 to n-1.

  • Array elements can be of any type, including an array type.

  • Array types are reference types derived from the abstract base type Array. Since this type implements IEnumerable and IEnumerable<(Of <(T>)>), you can use foreach iteration on all arrays in C#.