SoFunction
Updated on 2025-03-07

Convert C# byte to signed integer instance

C# development, receiving serial port data (temperature information) of the lower computer, which may be positive or negative. How to convert it?

The first reaction is to remember the theory in the book, the range of unsigned numbers is to what is the range of representation of signed numbers, which complicates the problem.

Don't forget the uint type:

uint raw = (uint)(bytes[7] * 256 + bytes[8]); //The actual situation of this project, use two bytes to represent the problem number

int wd = (int)raw;

Byte first transfer to uint, uint and then to int.

Supplementary knowledge:c# byte array conversion 8-bit signed integer 16-bit signed integer 32-bit signed integer

byte array

byte[] aa = new byte[] { 0xF8, 0x66, 0x55, 0x44 };

1. Convert to 8-bit signed integer

sbyte sb = (sbyte)aa[0];

2. Convert to 16-bit signed integer

Int16 int16 = BitConverter.ToInt16(aa, 0);

3. Convert to 32-bit signed integer

Int32 int32 = BitConverter.ToInt32(aa, 0);

The above example of converting C# byte to signed integer is all the content I have shared with you. I hope you can give you a reference and I hope you can support me more.