Netduino home hardware projects downloads community

Jump to content


The Netduino forums have been replaced by new forums at community.wildernesslabs.co. This site has been preserved for archival purposes only and the ability to make new accounts or posts has been turned off.
Photo

casting problem in C# from byte array to byte variable

casting byte array

  • Please log in to reply
2 replies to this topic

#1 oli4gate

oli4gate

    New Member

  • Members
  • Pip
  • 3 posts

Posted 10 January 2014 - 05:59 PM

Hi, I'm new to Netduino and C#

 

in my first project I have a casting problem.

 

this code :

byte checkSum = 0 ;byte[] dataFrame = new byte[5];checkSum = dataFrame[2] ^ dataFrame[3];

gives me this error : 

Cannot implicitly convert type 'int' into 'byte'. An explicit conversion exists (are you missing a cast?) 

 

 

but, this way, it works

byte checkSum = 0 ;byte[] dataFrame = new byte[5]; checkSum  = dataFrame[2];checkSum ^= dataFrame[3];

does anybody know why the first code doesn't work.

I would prefer to use only one line of code instead of two for this operation, and like to understand what went wrong?

 

tx,

Olivier

 



#2 Chris Walker

Chris Walker

    Secret Labs Staff

  • Moderators
  • 7767 posts
  • LocationNew York, NY

Posted 10 January 2014 - 07:42 PM

Hi Olivier, Try this:
byte checkSum = 0 ;byte[] dataFrame = new byte[5];checkSum = (byte)(dataFrame[2] ^ dataFrame[3]);
By explicitly casting the XOR result to a byte, the compiler will know that you are intentionally XOR'ing the two values within the limitations of the 8-bit byte type. Welcome to the Netduino community, Chris

#3 oli4gate

oli4gate

    New Member

  • Members
  • Pip
  • 3 posts

Posted 10 January 2014 - 11:14 PM

Thanks for the answer, Chris.

 

I tried your solution and it works fine!

 

Olivier






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

home    hardware    projects    downloads    community    where to buy    contact Copyright © 2016 Wilderness Labs Inc.  |  Legal   |   CC BY-SA
This webpage is licensed under a Creative Commons Attribution-ShareAlike License.