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

Recommended Answers

All 10 Replies

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

thanx for the reply. i got the above errors.. can you plese explain this..

Please post your code.

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);
        }
    }
}

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);
        }
    }
}

Thanx a lot nick...!!! It was really useful...!! Cheerss.........!!!!!!

Hi,
Would you please also mention 1's complement code?

Hi,
Would you please also mention 1's complement code?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.