Poznámka:
Přístup k této stránce vyžaduje autorizaci. Můžete se zkusit přihlásit nebo změnit adresáře.
Přístup k této stránce vyžaduje autorizaci. Můžete zkusit změnit adresáře.
Poznámka:
Tento článek obsahuje doplňující poznámky k referenční dokumentaci pro toto rozhraní API.
Byte je neměnný typ hodnoty, který představuje celá čísla bez znaménka s hodnotami v rozsahu 0 (který je reprezentován konstantou Byte.MinValue ) až 255 (který je reprezentován konstantou Byte.MaxValue ). Rozhraní .NET obsahuje také 8bitový podepsaný celočíselný typ hodnoty, SByte, který představuje hodnoty v rozsahu od -128 do 127.
Instancovat bajtovou hodnotu
Můžete vytvořit instanci hodnoty Byte několika způsoby:
Můžete deklarovat proměnnou Byte a přiřadit jí celočíselnou hodnotu literálu, která je v rozsahu datového Byte typu. Následující příklad deklaruje dvě Byte proměnné a tímto způsobem je přiřadí hodnotám.
byte value1 = 64; byte value2 = 255;let value1 = 64uy let value2 = 255uyDim value1 As Byte = 64 Dim value2 As Byte = 255K bajtu můžete přiřadit jinou než bajtovou číselnou hodnotu. Jedná se o zužující převod, takže vyžaduje operátor přetypování v jazyce C# a F# nebo metodu převodu v jazyce Visual Basic, pokud
Option Strictje zapnutá. Pokud je hodnota typu Single, Double nebo Decimal, která zahrnuje zlomkovou složku, zpracování její zlomkové části závisí na kompilátoru, který provádí převod. Následující příklad přiřadí několik číselných hodnot proměnným Byte.int int1 = 128; try { byte value1 = (byte)int1; Console.WriteLine(value1); } catch (OverflowException) { Console.WriteLine($"{int1} is out of range of a byte."); } double dbl2 = 3.997; try { byte value2 = (byte)dbl2; Console.WriteLine(value2); } catch (OverflowException) { Console.WriteLine($"{dbl2} is out of range of a byte."); } // The example displays the following output: // 128 // 3let int1 = 128 try let value1 = byte int1 printfn $"{value1}" with :? OverflowException -> printfn $"{int1} is out of range of a byte." let dbl2 = 3.997 try let value2 = byte dbl2 printfn $"{value2}" with :? OverflowException -> printfn $"{dbl2} is out of range of a byte." // The example displays the following output: // 128 // 3Dim int1 As Integer = 128 Try Dim value1 As Byte = CByte(int1) Console.WriteLine(value1) Catch e As OverflowException Console.WriteLine("{0} is out of range of a byte.", int1) End Try Dim dbl2 As Double = 3.997 Try Dim value2 As Byte = CByte(dbl2) Console.WriteLine(value2) Catch e As OverflowException Console.WriteLine("{0} is out of range of a byte.", dbl2) End Try ' The example displays the following output: ' 128 ' 4Metodu třídy Convert můžete použít k převodu libovolného podporovaného typu na hodnotu Byte. Je to možné, protože Byte podporuje rozhraní IConvertible. Následující příklad ukazuje převod pole Int32 hodnot na Byte hodnoty.
int[] numbers = { Int32.MinValue, -1, 0, 121, 340, Int32.MaxValue }; byte result; foreach (int number in numbers) { try { result = Convert.ToByte(number); Console.WriteLine($"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."); } catch (OverflowException) { Console.WriteLine($"The {number.GetType().Name} value {number} is outside the range of the Byte type."); } } // The example displays the following output: // The Int32 value -2147483648 is outside the range of the Byte type. // The Int32 value -1 is outside the range of the Byte type. // Converted the Int32 value 0 to the Byte value 0. // Converted the Int32 value 121 to the Byte value 121. // The Int32 value 340 is outside the range of the Byte type. // The Int32 value 2147483647 is outside the range of the Byte type.let numbers = [| Int32.MinValue; -1; 0; 121; 340; Int32.MaxValue |] for number in numbers do try let result = Convert.ToByte number printfn $"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}." with :? OverflowException -> printfn $"The {number.GetType().Name} value {number} is outside the range of the Byte type." // The example displays the following output: // The Int32 value -2147483648 is outside the range of the Byte type. // The Int32 value -1 is outside the range of the Byte type. // Converted the Int32 value 0 to the Byte value 0. // Converted the Int32 value 121 to the Byte value 121. // The Int32 value 340 is outside the range of the Byte type. // The Int32 value 2147483647 is outside the range of the Byte type.Dim numbers() As Integer = {Int32.MinValue, -1, 0, 121, 340, Int32.MaxValue} Dim result As Byte For Each number As Integer In numbers Try result = Convert.ToByte(number) Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", number.GetType().Name, number, result.GetType().Name, result) Catch e As OverflowException Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", number.GetType().Name, number) End Try Next ' The example displays the following output: ' The Int32 value -2147483648 is outside the range of the Byte type. ' The Int32 value -1 is outside the range of the Byte type. ' Converted the Int32 value 0 to the Byte value 0. ' Converted the Int32 value 121 to the Byte value 121. ' The Int32 value 340 is outside the range of the Byte type. ' The Int32 value 2147483647 is outside the range of the Byte type.Můžete volat metodu Parse nebo TryParse pro převod reprezentace řetězce hodnoty Byte na Byte. Řetězec může obsahovat desetinné nebo šestnáctkové číslice. Následující příklad znázorňuje operaci analýzy pomocí desítkového i šestnáctkového řetězce.
string string1 = "244"; try { byte byte1 = Byte.Parse(string1); Console.WriteLine(byte1); } catch (OverflowException) { Console.WriteLine($"'{string1}' is out of range of a byte."); } catch (FormatException) { Console.WriteLine($"'{string1}' is out of range of a byte."); } string string2 = "F9"; try { byte byte2 = Byte.Parse(string2, System.Globalization.NumberStyles.HexNumber); Console.WriteLine(byte2); } catch (OverflowException) { Console.WriteLine($"'{string2}' is out of range of a byte."); } catch (FormatException) { Console.WriteLine($"'{string2}' is out of range of a byte."); } // The example displays the following output: // 244 // 249let string1 = "244" try let byte1 = Byte.Parse string1 printfn $"{byte1}" with | :? OverflowException -> printfn $"'{string1}' is out of range of a byte." | :? FormatException -> printfn $"'{string1}' is out of range of a byte." let string2 = "F9" try let byte2 = Byte.Parse(string2, System.Globalization.NumberStyles.HexNumber) printfn $"{byte2}" with | :? OverflowException -> printfn $"'{string2}' is out of range of a byte." | :? FormatException -> printfn $"'{string2}' is out of range of a byte." // The example displays the following output: // 244 // 249Dim string1 As String = "244" Try Dim byte1 As Byte = Byte.Parse(string1) Console.WriteLine(byte1) Catch e As OverflowException Console.WriteLine("'{0}' is out of range of a byte.", string1) Catch e As FormatException Console.WriteLine("'{0}' is out of range of a byte.", string1) End Try Dim string2 As String = "F9" Try Dim byte2 As Byte = Byte.Parse(string2, System.Globalization.NumberStyles.HexNumber) Console.WriteLine(byte2) Catch e As OverflowException Console.WriteLine("'{0}' is out of range of a byte.", string2) Catch e As FormatException Console.WriteLine("'{0}' is out of range of a byte.", string2) End Try ' The example displays the following output: ' 244 ' 249
Provádění operací s hodnotami bajtů
Typ Byte podporuje standardní matematické operace, jako je sčítání, odčítání, dělení, násobení, odčítání, negace a unární negace. Stejně jako ostatní integrální typy podporuje typ Byte také bitové operátory AND, OR, XOR, posun vlevo a posun vpravo.
Standardní číselné operátory můžete použít k porovnání dvou Byte hodnot, nebo můžete zavolat metodu CompareTo nebo Equals.
Členy třídy Math můžete také volat pro provedení široké škály číselných operací, včetně získání absolutní hodnoty čísla, výpočtu kvocientu a zbytku z celočíselného dělení, určení maximální nebo minimální hodnoty dvou celých čísel, získání znaménka čísla a zaokrouhlení čísla.
Zobrazení byte jako řetězce
Typ Byte poskytuje úplnou podporu pro standardní a vlastní řetězce číselného formátu. (Další informace najdete v tématu Typy formátování, standardní řetězce číselného formátu a vlastní řetězce číselného formátu.) Nejčastěji se ale hodnoty bajtů reprezentují jako jednociferné až třímístné hodnoty bez dalšího formátování nebo jako dvouciferné šestnáctkové hodnoty.
Chcete-li naformátovat Byte hodnotu jako celočíselný řetězec bez počátečních nul, můžete volat metodu bez ToString() parametrů. Pomocí specifikátoru formátu "D" můžete do řetězcové reprezentace zahrnout také zadaný počet počátečních nul. Pomocí specifikátoru formátu "X" můžete reprezentovat Byte hodnotu jako šestnáctkový řetězec. Následující příklad formátuje prvky v poli Byte hodnot těmito třemi způsoby.
byte[] numbers = { 0, 16, 104, 213 };
foreach (byte number in numbers)
{
// Display value using default formatting.
Console.Write("{0,-3} --> ", number.ToString());
// Display value with 3 digits and leading zeros.
Console.Write(number.ToString("D3") + " ");
// Display value with hexadecimal.
Console.Write(number.ToString("X2") + " ");
// Display value with four hexadecimal digits.
Console.WriteLine(number.ToString("X4"));
}
// The example displays the following output:
// 0 --> 000 00 0000
// 16 --> 016 10 0010
// 104 --> 104 68 0068
// 213 --> 213 D5 00D5
let numbers = [| 0; 16; 104; 213 |]
for number in numbers do
// Display value using default formatting.
number.ToString()
|> printf "%-3s --> "
// Display value with 3 digits and leading zeros.
number.ToString "D3"
|> printf "%s "
// Display value with hexadecimal.
number.ToString "X2"
|> printf "%s "
// Display value with four hexadecimal digits.
number.ToString "X4"
|> printfn "%s"
// The example displays the following output:
// 0 --> 000 00 0000
// 16 --> 016 10 0010
// 104 --> 104 68 0068
// 213 --> 213 D5 00D5
Dim numbers() As Byte = {0, 16, 104, 213}
For Each number As Byte In numbers
' Display value using default formatting.
Console.Write("{0,-3} --> ", number.ToString())
' Display value with 3 digits and leading zeros.
Console.Write(number.ToString("D3") + " ")
' Display value with hexadecimal.
Console.Write(number.ToString("X2") + " ")
' Display value with four hexadecimal digits.
Console.WriteLine(number.ToString("X4"))
Next
' The example displays the following output:
' 0 --> 000 00 0000
' 16 --> 016 10 0010
' 104 --> 104 68 0068
' 213 --> 213 D5 00D5
Hodnotu můžete také naformátovat Byte jako binární, osmičkový, desetinný nebo šestnáctkový řetězec voláním ToString(Byte, Int32) metody a zadáním základu jako druhého parametru metody. Následující příklad volá tuto metodu, aby zobrazil binární, osmičková a šestnáctková reprezentace pole bajtových hodnot.
byte[] numbers = { 0, 16, 104, 213 };
Console.WriteLine("{0} {1,8} {2,5} {3,5}",
"Value", "Binary", "Octal", "Hex");
foreach (byte number in numbers)
{
Console.WriteLine("{0,5} {1,8} {2,5} {3,5}",
number, Convert.ToString(number, 2),
Convert.ToString(number, 8),
Convert.ToString(number, 16));
}
// The example displays the following output:
// Value Binary Octal Hex
// 0 0 0 0
// 16 10000 20 10
// 104 1101000 150 68
// 213 11010101 325 d5
let numbers = [| 0; 16; 104; 213 |]
printfn "%s %8s %5s %5s" "Value" "Binary" "Octal" "Hex"
for number in numbers do
printfn $"%5i{number} %8s{Convert.ToString(number, 2)} %5s{Convert.ToString(number, 8)} %5s{Convert.ToString(number, 16)}"
// The example displays the following output:
// Value Binary Octal Hex
// 0 0 0 0
// 16 10000 20 10
// 104 1101000 150 68
// 213 11010101 325 d5
Dim numbers() As Byte = {0, 16, 104, 213}
Console.WriteLine("{0} {1,8} {2,5} {3,5}",
"Value", "Binary", "Octal", "Hex")
For Each number As Byte In numbers
Console.WriteLine("{0,5} {1,8} {2,5} {3,5}",
number, Convert.ToString(number, 2),
Convert.ToString(number, 8),
Convert.ToString(number, 16))
Next
' The example displays the following output:
' Value Binary Octal Hex
' 0 0 0 0
' 16 10000 20 10
' 104 1101000 150 68
' 213 11010101 325 d5
Práce s bajtovými hodnotami v ne-desítkové soustavě
Kromě práce s jednotlivými bajty jako desetinnými hodnotami můžete chtít provádět bitové operace s bajtovými hodnotami nebo pracovat s bajtovými poli nebo s binární nebo šestnáctkovou reprezentací bajtů. Například přetížení BitConverter.GetBytes metody mohou převést každý z primitivních datových typů na bajtové pole a BigInteger.ToByteArray metoda převede BigInteger hodnotu na bajtové pole.
Byte hodnoty jsou reprezentovány v 8 bitech pouze jejich velikostí, bez znaménkového bitu. Je důležité mít na paměti, když provádíte bitové operace s Byte hodnotami nebo při práci s jednotlivými bity. Chcete-li provést číselnou, logickou nebo porovnávací operaci s libovolnými dvěma ne desetinnými hodnotami, musí obě hodnoty používat stejnou reprezentaci.
Když se operace provede se dvěma Byte hodnotami, hodnoty sdílejí stejnou reprezentaci, takže výsledek je přesný. To je znázorněno v následujícím příkladu, který maskuje bit nejnižšího řádu hodnoty Byte, aby se zajistilo, že je sudá.
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
string[] values = { Convert.ToString(12, 16),
Convert.ToString(123, 16),
Convert.ToString(245, 16) };
byte mask = 0xFE;
foreach (string value in values) {
Byte byteValue = Byte.Parse(value, NumberStyles.AllowHexSpecifier);
Console.WriteLine($"{byteValue} And {mask} = {byteValue & mask}");
}
}
}
// The example displays the following output:
// 12 And 254 = 12
// 123 And 254 = 122
// 245 And 254 = 244
open System
open System.Globalization
let values =
[ Convert.ToString(12, 16)
Convert.ToString(123, 16)
Convert.ToString(245, 16) ]
let mask = 0xFEuy
for value in values do
let byteValue = Byte.Parse(value, NumberStyles.AllowHexSpecifier)
printfn $"{byteValue} And {mask} = {byteValue &&& mask}"
// The example displays the following output:
// 12 And 254 = 12
// 123 And 254 = 122
// 245 And 254 = 244
Imports System.Globalization
Module Example1
Public Sub Main()
Dim values() As String = {Convert.ToString(12, 16),
Convert.ToString(123, 16),
Convert.ToString(245, 16)}
Dim mask As Byte = &HFE
For Each value As String In values
Dim byteValue As Byte = Byte.Parse(value, NumberStyles.AllowHexSpecifier)
Console.WriteLine("{0} And {1} = {2}", byteValue, mask,
byteValue And mask)
Next
End Sub
End Module
' The example displays the following output:
' 12 And 254 = 12
' 123 And 254 = 122
' 245 And 254 = 244
Na druhou stranu, když pracujete s nepodepsanými i podepsanými bity, bitové operace jsou složité tím, že SByte hodnoty používají pro kladné hodnoty vyjádření znaménka a velikosti a dvojkový doplněk pro záporné hodnoty. Aby bylo možné provést smysluplnou bitovou operaci, musí být hodnoty převedeny na dvě ekvivalentní reprezentace a informace o bitu znaménka musí být zachovány. Následující příklad provede maskování bitů 2 a 4 v poli s 8bitovými hodnotami se znaménkem a bez znaménka.
using System;
using System.Collections.Generic;
using System.Globalization;
public struct ByteString
{
public string Value;
public int Sign;
}
public class Example1
{
public static void Main()
{
ByteString[] values = CreateArray(-15, 123, 245);
byte mask = 0x14; // Mask all bits but 2 and 4.
foreach (ByteString strValue in values)
{
byte byteValue = Byte.Parse(strValue.Value, NumberStyles.AllowHexSpecifier);
Console.WriteLine($"{strValue.Sign * byteValue} ({Convert.ToString(byteValue, 2)}) And {mask} ({Convert.ToString(mask, 2)}) = {(strValue.Sign & Math.Sign(mask)) * (byteValue & mask)} ({Convert.ToString(byteValue & mask, 2)})");
}
}
private static ByteString[] CreateArray(params int[] values)
{
List<ByteString> byteStrings = new List<ByteString>();
foreach (object value in values)
{
ByteString temp = new ByteString();
int sign = Math.Sign((int)value);
temp.Sign = sign;
// Change two's complement to magnitude-only representation.
temp.Value = Convert.ToString(((int)value) * sign, 16);
byteStrings.Add(temp);
}
return byteStrings.ToArray();
}
}
// The example displays the following output:
// -15 (1111) And 20 (10100) = 4 (100)
// 123 (1111011) And 20 (10100) = 16 (10000)
// 245 (11110101) And 20 (10100) = 20 (10100)
open System
open System.Collections.Generic
open System.Globalization
[<Struct>]
type ByteString =
{ Sign: int
Value: string }
let createArray values =
[ for value in values do
let sign = sign value
{ Sign = sign
// Change two's complement to magnitude-only representation.
Value = Convert.ToString(value * sign, 16)} ]
let values = createArray [ -15; 123; 245 ]
let mask = 0x14uy // Mask all bits but 2 and 4.
for strValue in values do
let byteValue = Byte.Parse(strValue.Value, NumberStyles.AllowHexSpecifier)
printfn $"{strValue.Sign * int byteValue} ({Convert.ToString(byteValue, 2)}) And {mask} ({Convert.ToString(mask, 2)}) = {(strValue.Sign &&& (int mask |> sign)) * int (byteValue &&& mask)} ({Convert.ToString(byteValue &&& mask, 2)})"
// The example displays the following output:
// -15 (1111) And 20 (10100) = 4 (100)
// 123 (1111011) And 20 (10100) = 16 (10000)
// 245 (11110101) And 20 (10100) = 20 (10100)
Imports System.Collections.Generic
Imports System.Globalization
Public Structure ByteString
Public Value As String
Public Sign As Integer
End Structure
Module Example2
Public Sub Main()
Dim values() As ByteString = CreateArray(-15, 123, 245)
Dim mask As Byte = &H14 ' Mask all bits but 2 and 4.
For Each strValue As ByteString In values
Dim byteValue As Byte = Byte.Parse(strValue.Value, NumberStyles.AllowHexSpecifier)
Console.WriteLine("{0} ({1}) And {2} ({3}) = {4} ({5})",
strValue.Sign * byteValue,
Convert.ToString(byteValue, 2),
mask, Convert.ToString(mask, 2),
(strValue.Sign And Math.Sign(mask)) * (byteValue And mask),
Convert.ToString(byteValue And mask, 2))
Next
End Sub
Private Function CreateArray(ParamArray values() As Object) As ByteString()
Dim byteStrings As New List(Of ByteString)
For Each value As Object In values
Dim temp As New ByteString()
Dim sign As Integer = Math.Sign(value)
temp.Sign = sign
' Change two's complement to magnitude-only representation.
value = value * sign
temp.Value = Convert.ToString(value, 16)
byteStrings.Add(temp)
Next
Return byteStrings.ToArray()
End Function
End Module
' The example displays the following output:
' -15 (1111) And 20 (10100) = 4 (100)
' 123 (1111011) And 20 (10100) = 16 (10000)
' 245 (11110101) And 20 (10100) = 20 (10100)