#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    3
    Rep Power
    0

    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.
  2. #2
  3. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,117
    Rep Power
    1803
    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 03:13 PM.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    3
    Rep Power
    0
    Why does it assume I'm trying to add an int value to a byte when I'm clearly multiplying two byte values together?
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Loyal (3000 - 3499 posts)

    Join Date
    May 2004
    Posts
    3,417
    Rep Power
    887
    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

    • eramit2010 agrees
    Last edited by jwdonahue; July 28th, 2013 at 09:46 PM. Reason: spelling.
    I no longer wish to be associated with this site.

IMN logo majestic logo threadwatch logo seochat tools logo