July 28th, 2013, 10:30 AM
-
Working With Bytes
Hey guys,
I've been studying variables and started working with bytes but everytime I compile this simple code I get the error message;
Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)
This works perfectly with integers but why not bytes too?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyFirstProject
{
class Program
{
static void Main(string[] args)
{
byte a = 1,
b = 2,
c;
c = a + b;
Console.WriteLine(c);
}
}
}
Thanks from Cubies.
July 28th, 2013, 02:10 PM
-
The type of the expression a + b is int not byte, and you cannot assign a byte with an int without telling the compiler explicitly that it is intentional.
Code:
c = (byte)(a + b) ;
As ever RTFM :rolleyes:
Last edited by clifford; July 28th, 2013 at 02:13 PM.
July 28th, 2013, 02:36 PM
-
Why does it assume I'm trying to add an int value to a byte when I'm clearly multiplying two byte values together?
July 28th, 2013, 08:45 PM
-
Please learn to use code blocks to maintain proper code formatting.
In C#, when you add two bytes together the result is always an int. This is because you can't accurately store every result of a byte + byte operation in a byte due to potential overflow. Because C# will only implicitly convert to a larger size, you'll have to explicitly convert the result with a cast. You have three options:
c = checked( (byte)(a + b) ) ;
c = (byte)(a + b) ;
c = (byte)( (a + b) % 255 ) ;
The second unchecked variation is inherently unsafe and may not yield the results you expect. The third option also loses information and may or may not be equivalent the second.
Comments on this post
Last edited by jwdonahue; July 28th, 2013 at 08:46 PM.
Reason: spelling.
I no longer wish to be associated with this site.