What is the method for converting byte in C#?
In C#, you can utilize the static methods of the BitConverter class to convert a byte array into other data types. Here are some common method examples:
- Convert a byte array to an integer type.
byte[] byteArray = { 0x12, 0x34, 0x56, 0x78 };
int intValue = BitConverter.ToInt32(byteArray, 0);
- Convert byte array to long integer.
byte[] byteArray = { 0x12, 0x34, 0x56, 0x78 };
long longValue = BitConverter.ToInt64(byteArray, 0);
- Convert a byte array to a single-precision floating-point number.
byte[] byteArray = { 0x41, 0x48, 0xF5, 0xC3 };
float floatValue = BitConverter.ToSingle(byteArray, 0);
- Convert a byte array to a double-precision floating point number.
byte[] byteArray = { 0x40, 0x49, 0x0F, 0xDB, 0x22, 0xD0, 0x40, 0x49 };
double doubleValue = BitConverter.ToDouble(byteArray, 0);
- Convert a byte array to a boolean value:
byte[] byteArray = { 0x01 };
bool boolValue = BitConverter.ToBoolean(byteArray, 0);
Please note that the second parameter in the examples above indicates from which index in the byte array to begin the conversion.