0

I translated this line of code from Delphi:

byteSendData[4] := (byteSendData[1] + byteSendData[2] + byteSendData[3]) Mod 256;

into this in C#:

byteSendData[4] = (byteSendData[1] + byteSendData[2] + byteSendData[3]) % 256;

but VS returns me error I can't implicitly convert type 'int' into 'byte'.

ThorPowerx
  • 3
  • 1
  • 5
  • 2
    Do an unchecked cast to turn the result to a byte: `byteSendData[4] = unchecked( (byte)(byteSendData[1] + byteSendData[2] + byteSendData[3]) % 256);` – Matthew Watson Jan 10 '18 at 08:51
  • 1
    Also it's more traditional in C# to use `& 0xff` rather than `% 256` for masking. – Matthew Watson Jan 10 '18 at 08:52
  • I keep getting the same error even with your code: https://i.imgur.com/a2j3eWq.png – ThorPowerx Jan 10 '18 at 09:02
  • It was missing a set of parenthesis: It should have been `byteSendData[4] = unchecked( (byte)((byteSendData[1] + byteSendData[2] + byteSendData[3]) % 256));` – Matthew Watson Jan 10 '18 at 09:27
  • Ok, thanks a lot, but why that "unchecked" statement is so important? also, you would suggest me to use byteSendData[4] = unchecked( (byte)((byteSendData[1] + byteSendData[2] + byteSendData[3]) & 0xff)); right? what does & do exactly, can you link the manual? – ThorPowerx Jan 10 '18 at 09:52
  • `unchecked` is probably not necessary since you are restricting the result to 0..255 anyway, so you can omit that. The `&` is a [bitwise AND](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/and-operator). – Matthew Watson Jan 10 '18 at 12:00

1 Answers1

0

Use this

byteSendData[4] = Convert.ToByte((byteSendData[1] + byteSendData[2] + byteSendData[3]) % 256);


The thing is that you have a byte array byteSendData and the modulo calculation returns an integer. So just convert the result to byte. That's all.

Mark
  • 307
  • 2
  • 12
  • The thing is, the code gives me error even without the modulo part... Anyway I tryed your code and I still get the same error. – ThorPowerx Jan 10 '18 at 09:00