logo search
CSharp_Prog_Guide

Явные преобразования указателей

Из

В

Любой тип указателя

Любой другой тип указателя

sbyte, byte, short, ushort, int, uint, long или ulong

Любой тип указателя

Любой тип указателя

sbyte, byte, short, ushort, int, uint, long или ulong

Example

In the following example, a pointer to int is converted to a pointer to byte. Notice that the pointer points to the lowest addressed byte of the variable. When you successively increment the result, up to the size of int (4 bytes), you can display the remaining bytes of the variable.

// compile with: /unsafe

class ClassConvert

{

static void Main()

{

int number = 1024;

unsafe

{

// Convert to byte:

byte* p = (byte*)&number;

System.Console.Write("The 4 bytes of the integer:");

// Display the 4 bytes of the int variable:

for (int i = 0 ; i < sizeof(int) ; ++i)

{

System.Console.Write(" {0:X2}", *p);

// Increment the pointer:

p++;

}

System.Console.WriteLine();

System.Console.WriteLine("The value of the integer: {0}", number);

}

}

}

Output

The 4 bytes of the integer: 00 04 00 00

The value of the integer: 1024

Пример

В следующем пример указатель на int преобразуется в указатель на byte. Обратите внимание на то, что указатель указывает на наименьший адресуемый байт переменной. При последовательном увеличении результата до размера int (4 байта) можно отобразить оставшиеся байты переменной.

-----