milnuts milnuts - 1 month ago 22
C# Question

Converting Byte[] to a Int8

Is there any way to convert a Byte[] into a int8? I have been given a binary file that contains a list of input parameters for a test. The parameters vary in size from uint32 down to uint8. I am having no problem reading in the file, what is tricky is getting the values to display in the GUI.

Here's is the basis of what I'm doing:

private Byte[] blockSize;
private Byte[] binSize;

FileStream filen = File.OpenRead(file);
BinaryReader br = new BinaryReader(filen);

blockSize = br.ReadBytes(4);
binSize = br.ReadBytes(1);


No problems with that considering that the first 32 bits (4 bytes) of the parameter file are the blockSize and the next 8 bits (1 byte) are the value for my binSize variable. Where the problem comes is in displaying it.

textBox1.Text = BitConverter.ToInt32(blockSize, 0).ToString();
textBox2.Text = BitConverter.ToString(binSize, 0).ToString();


Lets say that my binary input file contains the following 5 bytes of data "0A 00 00 00 0A". My first textbox displays '10', my second textbox displays '0A'. I want the hex value converted into the more human understandable decimal value. It seems to work fine as long as the parameter in the input file is greater than 1 byte so I can easily convert it using ToInt16 or ToInt32, but I have nothing for the 8bit variety.

Answer

Your problem that r.ReadBytes(1); return byte[] then your call BitConverter.ToString(bytearray) with byte array as parameter which do the next:

Converts the numeric value of each element of a specified array of bytes to its equivalent hexadecimal string representation

BinaryReader has methods

int ReadInt32()
byte ReadByte()

Change types of blockSize to int and binSize to byte and use those methods

int blockSize = br.ReadInt32();
byte binSize = br.ReadByte();

textBox1.Text = blockSize.ToString();
textBox2.Text = binSize.ToString();

From MSDN:
ReadInt32()

Reads a 4-byte signed integer from the current stream and advances the current position of the stream by four bytes.

ReadByte()

Reads the next byte from the current stream and advances the current position of the stream by one byte.

Comments