I am currently doing a project and am a novice to c#. I have a problem where i receive serial 'dataframes', each consisting of two
8-bit values (the high byte and the low byte), which have to be
constructed to get a 16-bit value. This assembled value is already in
two's complement and I need to get the original value.

eg :- 1. LowByte = 0xFE HighByte = 0xFF Answer should equal -2
2. LowByte = 0x03 HighByte = 0x00 Answer should equal +3

Try this

byte[] data = new byte[2];
data[0] = 0xFE;
data[1] = 0xFF;
short value = System.BitConverter.ToInt16(data, 0);

Error 1 Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
Error 2 Invalid token '=' in class, struct, or interface member declaration

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {

        byte[] data = new byte[2];
        data[0] = 0xFE;
        data[1] = 0xFF;
        
        public Form1()
        {
            InitializeComponent();
        }

        

        private void button1_Click(object sender, EventArgs e)
        {
            short value = System.BitConverter.ToInt16(data, 0);
            label1.Text = Convert.ToString(value);
        }
    }
}

Edited 6 Years Ago by __avd: Added [code] tags. For easy readability, always wrap programming code within posts in [code] (code blocks).

I tried this example before applying ti it my project. I have inserted only one button and one lable...

OK.

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        byte[] data = new byte[2]; //<- this bit is delaring and initialising a variable
                                   //    this is OK at form level

        data[0] = 0xFE;            //<- these are assigning a value to a variable
        data[1] = 0xFF;            //     this is NOT OK at form level
                                   //    move these into the button1_Click method

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            short value = System.BitConverter.ToInt16(data, 0);
            label1.Text = Convert.ToString(value);
        }
    }
}
This article has been dead for over six months. Start a new discussion instead.