Byte Estructura
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Representa un entero de 8 bits sin signo.
public value class System::Byte : IComparable, IComparable<System::Byte>, IConvertible, IEquatable<System::Byte>, IFormattable
public value class System::Byte : IComparable, IComparable<System::Byte>, IConvertible, IEquatable<System::Byte>, ISpanFormattable
public value class System::Byte : IComparable<System::Byte>, IConvertible, IEquatable<System::Byte>, IParsable<System::Byte>, ISpanParsable<System::Byte>, System::Numerics::IAdditionOperators<System::Byte, System::Byte, System::Byte>, System::Numerics::IAdditiveIdentity<System::Byte, System::Byte>, System::Numerics::IBinaryInteger<System::Byte>, System::Numerics::IBinaryNumber<System::Byte>, System::Numerics::IBitwiseOperators<System::Byte, System::Byte, System::Byte>, System::Numerics::IComparisonOperators<System::Byte, System::Byte, bool>, System::Numerics::IDecrementOperators<System::Byte>, System::Numerics::IDivisionOperators<System::Byte, System::Byte, System::Byte>, System::Numerics::IEqualityOperators<System::Byte, System::Byte, bool>, System::Numerics::IIncrementOperators<System::Byte>, System::Numerics::IMinMaxValue<System::Byte>, System::Numerics::IModulusOperators<System::Byte, System::Byte, System::Byte>, System::Numerics::IMultiplicativeIdentity<System::Byte, System::Byte>, System::Numerics::IMultiplyOperators<System::Byte, System::Byte, System::Byte>, System::Numerics::INumber<System::Byte>, System::Numerics::INumberBase<System::Byte>, System::Numerics::IShiftOperators<System::Byte, int, System::Byte>, System::Numerics::ISubtractionOperators<System::Byte, System::Byte, System::Byte>, System::Numerics::IUnaryNegationOperators<System::Byte, System::Byte>, System::Numerics::IUnaryPlusOperators<System::Byte, System::Byte>, System::Numerics::IUnsignedNumber<System::Byte>
public value class System::Byte : IComparable, IConvertible, IFormattable
public value class System::Byte : IComparable, IComparable<System::Byte>, IEquatable<System::Byte>, IFormattable
public struct Byte : IComparable, IComparable<byte>, IConvertible, IEquatable<byte>, IFormattable
public readonly struct Byte : IComparable, IComparable<byte>, IConvertible, IEquatable<byte>, IFormattable
public readonly struct Byte : IComparable, IComparable<byte>, IConvertible, IEquatable<byte>, ISpanFormattable
public readonly struct Byte : IComparable<byte>, IConvertible, IEquatable<byte>, IParsable<byte>, ISpanParsable<byte>, System.Numerics.IAdditionOperators<byte,byte,byte>, System.Numerics.IAdditiveIdentity<byte,byte>, System.Numerics.IBinaryInteger<byte>, System.Numerics.IBinaryNumber<byte>, System.Numerics.IBitwiseOperators<byte,byte,byte>, System.Numerics.IComparisonOperators<byte,byte,bool>, System.Numerics.IDecrementOperators<byte>, System.Numerics.IDivisionOperators<byte,byte,byte>, System.Numerics.IEqualityOperators<byte,byte,bool>, System.Numerics.IIncrementOperators<byte>, System.Numerics.IMinMaxValue<byte>, System.Numerics.IModulusOperators<byte,byte,byte>, System.Numerics.IMultiplicativeIdentity<byte,byte>, System.Numerics.IMultiplyOperators<byte,byte,byte>, System.Numerics.INumber<byte>, System.Numerics.INumberBase<byte>, System.Numerics.IShiftOperators<byte,int,byte>, System.Numerics.ISubtractionOperators<byte,byte,byte>, System.Numerics.IUnaryNegationOperators<byte,byte>, System.Numerics.IUnaryPlusOperators<byte,byte>, System.Numerics.IUnsignedNumber<byte>
[System.Serializable]
public struct Byte : IComparable, IConvertible, IFormattable
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public struct Byte : IComparable, IComparable<byte>, IConvertible, IEquatable<byte>, IFormattable
public struct Byte : IComparable, IComparable<byte>, IEquatable<byte>, IFormattable
type byte = struct
interface IConvertible
interface IFormattable
type byte = struct
interface IConvertible
interface ISpanFormattable
interface IFormattable
type byte = struct
interface IConvertible
interface IFormattable
interface IParsable<byte>
interface ISpanFormattable
interface ISpanParsable<byte>
interface IAdditionOperators<byte, byte, byte>
interface IAdditiveIdentity<byte, byte>
interface IBinaryInteger<byte>
interface IBinaryNumber<byte>
interface IBitwiseOperators<byte, byte, byte>
interface IComparisonOperators<byte, byte, bool>
interface IEqualityOperators<byte, byte, bool>
interface IDecrementOperators<byte>
interface IDivisionOperators<byte, byte, byte>
interface IIncrementOperators<byte>
interface IModulusOperators<byte, byte, byte>
interface IMultiplicativeIdentity<byte, byte>
interface IMultiplyOperators<byte, byte, byte>
interface INumber<byte>
interface INumberBase<byte>
interface ISubtractionOperators<byte, byte, byte>
interface IUnaryNegationOperators<byte, byte>
interface IUnaryPlusOperators<byte, byte>
interface IShiftOperators<byte, int, byte>
interface IMinMaxValue<byte>
interface IUnsignedNumber<byte>
[<System.Serializable>]
type byte = struct
interface IFormattable
interface IConvertible
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type byte = struct
interface IFormattable
interface IConvertible
type byte = struct
interface IFormattable
Public Structure Byte
Implements IComparable, IComparable(Of Byte), IConvertible, IEquatable(Of Byte), IFormattable
Public Structure Byte
Implements IComparable, IComparable(Of Byte), IConvertible, IEquatable(Of Byte), ISpanFormattable
Public Structure Byte
Implements IAdditionOperators(Of Byte, Byte, Byte), IAdditiveIdentity(Of Byte, Byte), IBinaryInteger(Of Byte), IBinaryNumber(Of Byte), IBitwiseOperators(Of Byte, Byte, Byte), IComparable(Of Byte), IComparisonOperators(Of Byte, Byte, Boolean), IConvertible, IDecrementOperators(Of Byte), IDivisionOperators(Of Byte, Byte, Byte), IEqualityOperators(Of Byte, Byte, Boolean), IEquatable(Of Byte), IIncrementOperators(Of Byte), IMinMaxValue(Of Byte), IModulusOperators(Of Byte, Byte, Byte), IMultiplicativeIdentity(Of Byte, Byte), IMultiplyOperators(Of Byte, Byte, Byte), INumber(Of Byte), INumberBase(Of Byte), IParsable(Of Byte), IShiftOperators(Of Byte, Integer, Byte), ISpanParsable(Of Byte), ISubtractionOperators(Of Byte, Byte, Byte), IUnaryNegationOperators(Of Byte, Byte), IUnaryPlusOperators(Of Byte, Byte), IUnsignedNumber(Of Byte)
Public Structure Byte
Implements IComparable, IConvertible, IFormattable
Public Structure Byte
Implements IComparable, IComparable(Of Byte), IEquatable(Of Byte), IFormattable
- Herencia
- Atributos
- Implementaciones
-
IComparable IComparable<Byte> IConvertible IEquatable<Byte> IFormattable ISpanFormattable IComparable<TSelf> IEquatable<TSelf> IParsable<Byte> IParsable<TSelf> ISpanParsable<Byte> ISpanParsable<TSelf> IAdditionOperators<Byte,Byte,Byte> IAdditionOperators<TSelf,TSelf,TSelf> IAdditiveIdentity<Byte,Byte> IAdditiveIdentity<TSelf,TSelf> IBinaryInteger<Byte> IBinaryNumber<Byte> IBinaryNumber<TSelf> IBitwiseOperators<Byte,Byte,Byte> IBitwiseOperators<TSelf,TSelf,TSelf> IComparisonOperators<Byte,Byte,Boolean> IComparisonOperators<TSelf,TSelf,Boolean> IDecrementOperators<Byte> IDecrementOperators<TSelf> IDivisionOperators<Byte,Byte,Byte> IDivisionOperators<TSelf,TSelf,TSelf> IEqualityOperators<Byte,Byte,Boolean> IEqualityOperators<TSelf,TOther,TResult> IEqualityOperators<TSelf,TSelf,Boolean> IIncrementOperators<Byte> IIncrementOperators<TSelf> IMinMaxValue<Byte> IModulusOperators<Byte,Byte,Byte> IModulusOperators<TSelf,TSelf,TSelf> IMultiplicativeIdentity<Byte,Byte> IMultiplicativeIdentity<TSelf,TSelf> IMultiplyOperators<Byte,Byte,Byte> IMultiplyOperators<TSelf,TSelf,TSelf> INumber<Byte> INumber<TSelf> INumberBase<Byte> INumberBase<TSelf> IShiftOperators<Byte,Int32,Byte> IShiftOperators<TSelf,Int32,TSelf> ISubtractionOperators<Byte,Byte,Byte> ISubtractionOperators<TSelf,TSelf,TSelf> IUnaryNegationOperators<Byte,Byte> IUnaryNegationOperators<TSelf,TSelf> IUnaryPlusOperators<Byte,Byte> IUnaryPlusOperators<TSelf,TSelf> IUnsignedNumber<Byte>
Comentarios
Byte es un tipo de valor inmutable que representa enteros sin signo con valores que van de 0 (representados por la Byte.MinValue constante) a 255 (representados por la Byte.MaxValue constante). .NET también incluye un tipo de valor entero de 8 bits con signo, SByte, que representa valores que van de -128 a 127.
Creación de instancias de un valor de byte
Puede crear una instancia de un Byte valor de varias maneras:
Puede declarar una Byte variable y asignarle un valor entero literal que se encuentra dentro del intervalo del tipo de Byte datos. En el ejemplo siguiente se declaran dos Byte variables y se les asignan valores de esta manera.
byte value1 = 64; byte value2 = 255;
let value1 = 64uy let value2 = 255uy
Dim value1 As Byte = 64 Dim value2 As Byte = 255
Puede asignar un valor numérico no byte a un byte. Se trata de una conversión de restricción, por lo que requiere un operador de conversión en C# y F#, o un método de conversión en Visual Basic si
Option Strict
está activado. Si el valor que no es de byte es un Singlevalor , Doubleo Decimal que incluye un componente fraccionado, el control de su parte fraccionarcional depende del compilador que realiza la conversión. En el ejemplo siguiente se asignan varios valores numéricos a Byte variables.int int1 = 128; try { byte value1 = (byte) int1; Console.WriteLine(value1); } catch (OverflowException) { Console.WriteLine("{0} is out of range of a byte.", int1); } double dbl2 = 3.997; try { byte value2 = (byte) dbl2; Console.WriteLine(value2); } catch (OverflowException) { Console.WriteLine("{0} is out of range of a byte.", dbl2); } // The example displays the following output: // 128 // 3
let 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 // 3
Dim 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 ' 4
Puede llamar a un método de la Convert clase para convertir cualquier tipo admitido en un Byte valor. Esto es posible porque Byte admite la IConvertible interfaz . En el ejemplo siguiente se muestra la conversión de una matriz de Int32 valores a Byte valores.
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 {0} value {1} to the {2} value {3}.", number.GetType().Name, number, result.GetType().Name, result); } catch (OverflowException) { Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", number.GetType().Name, number); } } // 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.
open System 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.
Puede llamar al Parse método o TryParse para convertir la representación de cadena de un Byte valor en .Byte La cadena puede contener dígitos decimales o hexadecimales. En el ejemplo siguiente se muestra la operación de análisis mediante una cadena decimal y hexadecimal.
string string1 = "244"; try { byte byte1 = Byte.Parse(string1); Console.WriteLine(byte1); } catch (OverflowException) { Console.WriteLine("'{0}' is out of range of a byte.", string1); } catch (FormatException) { Console.WriteLine("'{0}' is out of range of a byte.", string1); } string string2 = "F9"; try { byte byte2 = Byte.Parse(string2, System.Globalization.NumberStyles.HexNumber); Console.WriteLine(byte2); } catch (OverflowException) { Console.WriteLine("'{0}' is out of range of a byte.", string2); } catch (FormatException) { Console.WriteLine("'{0}' is out of range of a byte.", string2); } // The example displays the following output: // 244 // 249
let 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 // 249
Dim 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
Realizar operaciones en valores de bytes
El Byte tipo admite operaciones matemáticas estándar, como suma, resta, división, multiplicación, resta, negación y negación unaria. Al igual que los demás tipos enteros, el Byte tipo también admite los operadores bit a bit AND
, OR
, , XOR
desplazamiento a la izquierda y desplazamiento derecho.
Puede usar los operadores numéricos estándar para comparar dos Byte valores o puede llamar al CompareTo método o Equals .
También puede llamar a los miembros de la Math clase para realizar una amplia gama de operaciones numéricas, incluida la obtención del valor absoluto de un número, el cálculo del cociente y el resto de la división integral, determinar el valor máximo o mínimo de dos enteros, obtener el signo de un número y redondear un número.
Representar un byte como una cadena
El Byte tipo proporciona compatibilidad completa con cadenas de formato numérico estándar y personalizado. (Para obtener más información, vea Tipos de formato, cadenas de formato numérico estándar y cadenas de formato numérico personalizado). Sin embargo, normalmente, los valores de bytes se representan como valores de un dígito a tres dígitos sin formato adicional o como valores hexadecimales de dos dígitos.
Para dar formato a un Byte valor como una cadena integral sin ceros a la izquierda, puede llamar al método sin ToString() parámetros. Mediante el especificador de formato "D", también puede incluir un número especificado de ceros a la izquierda en la representación de cadena. Mediante el especificador de formato "X", puede representar un Byte valor como una cadena hexadecimal. En el ejemplo siguiente se da formato a los elementos de una matriz de valores de Byte estas tres maneras.
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
También puede dar formato a un valor como una Byte cadena binaria, octal, decimal o hexadecimal llamando al ToString(Byte, Int32) método y proporcionando la base como segundo parámetro del método. En el ejemplo siguiente se llama a este método para mostrar las representaciones binarias, octales y hexadecimales de una matriz de valores de bytes.
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
Trabajar con valores de bytes no decimales
Además de trabajar con bytes individuales como valores decimales, es posible que desee realizar operaciones bit a bit con valores de bytes, o trabajar con matrices de bytes o con las representaciones binarias o hexadecimales de los valores de bytes. Por ejemplo, las sobrecargas del BitConverter.GetBytes método pueden convertir cada uno de los tipos de datos primitivos en una matriz de bytes y el BigInteger.ToByteArray método convierte un BigInteger valor en una matriz de bytes.
Byte los valores solo se representan en 8 bits por su magnitud, sin un bit de signo. Esto es importante tener en cuenta cuando se realizan operaciones bit a bit en Byte valores o cuando se trabaja con bits individuales. Para realizar una operación numérica, booleana o de comparación en dos valores no decimales, ambos valores deben usar la misma representación.
Cuando se realiza una operación en dos Byte valores, los valores comparten la misma representación, por lo que el resultado es preciso. Esto se ilustra en el ejemplo siguiente, que enmascara el bit de orden más bajo de un Byte valor para asegurarse de que es uniforme.
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("{0} And {1} = {2}", byteValue, 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 Example
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
Por otro lado, cuando se trabaja con bits sin signo y con signo, las operaciones bit a bit son complicadas por el hecho de que los SByte valores usan la representación de signo y magnitud para valores positivos y la representación complementaria de dos para valores negativos. Para realizar una operación bit a bit significativa, los valores deben convertirse en dos representaciones equivalentes y se debe conservar la información sobre el bit de signo. En el ejemplo siguiente se hace esto para enmascarar los bits 2 y 4 de una matriz de valores con signo y sin signo de 8 bits.
using System;
using System.Collections.Generic;
using System.Globalization;
public struct ByteString
{
public string Value;
public int Sign;
}
public class Example
{
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("{0} ({1}) And {2} ({3}) = {4} ({5})",
strValue.Sign * byteValue,
Convert.ToString(byteValue, 2),
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 Example
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)
Campos
MaxValue |
Representa el mayor valor posible de un Byte. Este campo es constante. |
MinValue |
Representa el menor valor posible de un Byte. Este campo es constante. |
Métodos
Clamp(Byte, Byte, Byte) |
Fija un valor en un valor mínimo inclusivo y máximo. |
CompareTo(Byte) |
Compara esta instancia con un entero de 8 bits sin signo y devuelve una indicación de los valores relativos. |
CompareTo(Object) |
Compara esta instancia con un objeto especificado y devuelve una indicación de los valores relativos. |
CreateChecked<TOther>(TOther) |
Crea una instancia del tipo actual a partir de un valor, lo que produce una excepción de desbordamiento para los valores que se encuentran fuera del intervalo que se puede representar del tipo actual. |
CreateSaturating<TOther>(TOther) |
Crea una instancia del tipo actual a partir de un valor, saturando los valores que se encuentran fuera del intervalo representable del tipo actual. |
CreateTruncating<TOther>(TOther) |
Crea una instancia del tipo actual a partir de un valor, truncando los valores que se encuentran fuera del intervalo que se puede representar del tipo actual. |
DivRem(Byte, Byte) |
Calcula el cociente y el resto de dos valores. |
Equals(Byte) |
Devuelve un valor que indica si esta instancia y un objeto Byte especificado representan el mismo valor. |
Equals(Object) |
Devuelve un valor que indica si esta instancia equivale a un objeto especificado. |
GetHashCode() |
Devuelve el código hash de esta instancia. |
GetTypeCode() | |
IsEvenInteger(Byte) |
Determina si un valor representa un número entero par. |
IsOddInteger(Byte) |
Determina si un valor representa un número entero impar. |
IsPow2(Byte) |
Determina si un valor es una potencia de dos. |
LeadingZeroCount(Byte) |
Calcula el número de ceros a la izquierda en un valor. |
Log2(Byte) |
Calcula el registro2 de un valor. |
Max(Byte, Byte) |
Compara dos valores con el proceso, que es mayor. |
Min(Byte, Byte) |
Compara dos valores con el proceso, que es menor. |
Parse(ReadOnlySpan<Char>, IFormatProvider) |
Analiza un intervalo de caracteres en un valor. |
Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) |
Convierte la representación del intervalo de un número con el estilo y el formato específicos de la referencia cultural especificados en su equivalente de Byte. |
Parse(String) |
Convierte la representación en forma de cadena de un número en su Byte equivalente. |
Parse(String, IFormatProvider) |
Convierte la representación en forma de cadena de un número con el formato específico de la referencia cultural indicada en su Byte equivalente. |
Parse(String, NumberStyles) |
Convierte la representación de cadena de un número con un estilo especificado en su Byte equivalente. |
Parse(String, NumberStyles, IFormatProvider) |
Convierte la representación de cadena de un número con el estilo y el formato específico de la referencia cultural que se hayan especificado en su equivalente de Byte. |
PopCount(Byte) |
Calcula el número de bits establecidos en un valor. |
RotateLeft(Byte, Int32) |
Gira un valor de izquierda por una cantidad determinada. |
RotateRight(Byte, Int32) |
Gira un valor a la derecha por una cantidad determinada. |
Sign(Byte) |
Calcula el signo de un valor. |
ToString() |
Convierte el valor del objeto Byte actual en su representación de cadena equivalente. |
ToString(IFormatProvider) |
Convierte el valor numérico del objeto Byte actual en su representación de cadena equivalente usando la información de formato específica de la referencia cultural especificada. |
ToString(String) |
Convierte el valor del objeto Byte actual en su representación de cadena equivalente usando el formato especificado. |
ToString(String, IFormatProvider) |
Convierte el valor del objeto Byte actual en la representación de cadena equivalente usando el formato y la información de formato específica de la referencia cultural especificados. |
TrailingZeroCount(Byte) |
Calcula el número de ceros finales en un valor. |
TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider) |
Intenta dar formato al valor de la instancia de entero sin signo de 8 bits actual en el intervalo de caracteres proporcionado. |
TryParse(ReadOnlySpan<Char>, Byte) |
Intenta convertir la representación de intervalo de un número en su valor Byte equivalente y devuelve un valor que indica si la conversión se ha realizado correctamente. |
TryParse(ReadOnlySpan<Char>, IFormatProvider, Byte) |
Intenta analizar un intervalo de caracteres en un valor. |
TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Byte) |
Convierte la representación del intervalo de un número con el estilo y el formato específicos de la referencia cultural especificados en su equivalente de Byte. Un valor devuelto indica si la conversión se realizó correctamente o si se produjeron errores. |
TryParse(String, Byte) |
Intenta convertir la representación en forma de cadena de un número en su equivalente Byte y devuelve un valor que indica si la conversión tuvo éxito. |
TryParse(String, IFormatProvider, Byte) |
Intenta analizar una cadena en un valor. |
TryParse(String, NumberStyles, IFormatProvider, Byte) |
Convierte la representación de cadena de un número con el estilo y el formato específico de la referencia cultural que se hayan especificado en su equivalente de Byte. Un valor devuelto indica si la conversión se realizó correctamente o si se produjeron errores. |
Implementaciones de interfaz explícitas
IBinaryInteger<Byte>.GetByteCount() |
Obtiene el número de bytes que se escribirán como parte de TryWriteLittleEndian(Span<Byte>, Int32). |
IBinaryInteger<Byte>.GetShortestBitLength() |
Obtiene la longitud, en bits, de la representación complementaria de dos más corta del valor actual. |
IBinaryInteger<Byte>.TryWriteBigEndian(Span<Byte>, Int32) |
Intenta escribir el valor actual, en formato big-endian, en un intervalo determinado. |
IBinaryInteger<Byte>.TryWriteLittleEndian(Span<Byte>, Int32) |
Intenta escribir el valor actual, en formato little-endian, en un intervalo determinado. |
IComparable.CompareTo(Object) |
Compara la instancia actual con otro objeto del mismo tipo y devuelve un entero que indica si la posición de la instancia actual es anterior, posterior o igual que la del otro objeto en el criterio de ordenación. |
IConvertible.GetTypeCode() |
Devuelve el TypeCode para esta instancia. |
IConvertible.ToBoolean(IFormatProvider) |
Para obtener una descripción de este miembro, vea ToBoolean(IFormatProvider). |
IConvertible.ToByte(IFormatProvider) |
Para obtener una descripción de este miembro, vea ToByte(IFormatProvider). |
IConvertible.ToChar(IFormatProvider) |
Para obtener una descripción de este miembro, vea ToChar(IFormatProvider). |
IConvertible.ToDateTime(IFormatProvider) |
No se admite esta conversión. Cualquier intento de usar este método produce una excepción InvalidCastException. |
IConvertible.ToDecimal(IFormatProvider) |
Para obtener una descripción de este miembro, vea ToDecimal(IFormatProvider). |
IConvertible.ToDouble(IFormatProvider) |
Para obtener una descripción de este miembro, vea ToDouble(IFormatProvider). |
IConvertible.ToInt16(IFormatProvider) |
Para obtener una descripción de este miembro, vea ToInt16(IFormatProvider). |
IConvertible.ToInt32(IFormatProvider) |
Para obtener una descripción de este miembro, vea ToInt32(IFormatProvider). |
IConvertible.ToInt64(IFormatProvider) |
Para obtener una descripción de este miembro, vea ToInt64(IFormatProvider). |
IConvertible.ToSByte(IFormatProvider) |
Para obtener una descripción de este miembro, vea ToSByte(IFormatProvider). |
IConvertible.ToSingle(IFormatProvider) |
Para obtener una descripción de este miembro, vea ToSingle(IFormatProvider). |
IConvertible.ToType(Type, IFormatProvider) |
Para obtener una descripción de este miembro, vea ToType(Type, IFormatProvider). |
IConvertible.ToUInt16(IFormatProvider) |
Para obtener una descripción de este miembro, vea ToUInt16(IFormatProvider). |
IConvertible.ToUInt32(IFormatProvider) |
Para obtener una descripción de este miembro, vea ToUInt32(IFormatProvider). |
IConvertible.ToUInt64(IFormatProvider) |
Para obtener una descripción de este miembro, vea ToUInt64(IFormatProvider). |
Se aplica a
Seguridad para subprocesos
Todos los miembros de este tipo son seguros para subprocesos. Los miembros que parecen modificar el estado de instancia devuelven realmente una nueva instancia inicializada con el nuevo valor. Al igual que con cualquier otro tipo, leer y escribir en una variable compartida que contenga una instancia de este tipo debe estar protegida por un bloqueo para garantizar la seguridad de los subprocesos.