Steven Wilson
Steven Wilson

Reputation: 139

Operator '+' cannot be applied to operands of type 'byte[]' and 'int'

I am a C++ developer and recently moved to C#. Now I am dealing with a textbox in my WPF app where I need to set the test of the textbox. Here is the code:

XAML:

<TextBox Name="Data11" MaxLength="2" Grid.Column="0" Text="{Binding Data11}" />
<TextBox Name="Data12" MaxLength="2" Grid.Column="1" Text="{Binding Data12}" />

ViewModel Class:

private string _Data11;
    public string Data11
    {
        get
        {
            return _Data11;
        }

        set
        {
            _Data11 = value;
            OnPropertyChanged("Data11");
        }
    }

// Description of Data12
private string _Data12;
public string Data12
{
    get
    {
        return _Data12;
    }

    set
    {
        _Data12 = value;
        OnPropertyChanged("Data12");
    }
}

Now on this textbox I need to set the text. Basically In my C++ app I had done it as follows:

m_matchData11->setText(String(String::toHexString((buffer+0), 1)), false);
m_matchData12->setText(String(String::toHexString((buffer+1+4), 1)), false);

If you notice above, ToHexString Creates a string containing a hex dump of a block of binary data. I tried doing this in My WPF app as follows:

Data11 = BitConverter.ToString(buffer, 1);
Data12 = BitConverter.ToString((buffer + 4), 1);

Although first statement seems to work fine, second one throws the following error:

Operator '+' cannot be applied to operands of type 'byte[]' and 'int'

How can I achieve it? :)

Upvotes: 1

Views: 2595

Answers (1)

Matthew
Matthew

Reputation: 25763

You can use the overload of the BitConverter.ToString method which accepts a starting index and length.

Data12 = BitConverter.ToString(buffer, 4, 1);

This will get the 5th byte in the buffer.

If you were not using BitConverter.ToString and had to do manual manipulation, you can use Linq's Take and Skip extension methods.

EDIT:

If you're only ever formatting 1 byte of the buffer, you may be able to do this instead:

Data12 = buffer[4].ToString("X2");

Upvotes: 4

Related Questions