Вопрос

I have something like this in c#

        byte a;
        byte b;
        byte c;

        c = a + b;

and it gives an error for c = a + b and says "Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?). I don't understand why because everything is in bytes

Matlab is involved because I am translating an image processing program from matlab into c# where i take values from a picture which are uint8 and doing calculations with that value when it does it the unit8 takes over and during any calculations any number higher than 255 is set to 255. So in c# I just made all of my variables bytes since they are all under 255 anyways but just like in the example code when running the calculations the error pops up.

Это было полезно?

Решение 2

During any calculations any number higher than 255 is set to 255.

This is not supported natively in C#. Instead, the default behaviour of the (byte) cast is to take the least significant byte, giving an arithmetic result equivalent to modulo 256.

c = unchecked((byte)(200 + 200));

The result above will be 144, which is equivalent to 400 % 256.

If you want to clip results at 255, you need to specify this explicitly:

c = (byte)Math.Min(a + b, 255);

Другие советы

The arithmetic expression on the right-hand side of the assignment operator evaluates to int by default.

See byte - MSDN

The following assignment statement will produce a compilation error, because the arithmetic expression on the right-hand side of the assignment operator evaluates to int by default.

byte x = 10, y = 20;
byte z = x + y;   // Error: conversion from int to byte

By adding an explicit cast the error will go like:

byte z = (byte)(x + y);   
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top