How to add 1 byte

I tried

module Program { Main() : void { mutable x : byte = 0B; mutable y : byte = 0B; x++; //y = x + 1; //y = x + 1B; //def one:byte=1;// x = x + one; } } 

No matter what I try with, I get the following error message.

Error 1 expected byte received by int at the assigned value: System.Int32 is not a subtype of System.Byte [simple require]

The only way I found that works

  y = ( x + 1 ):>byte 

Which bit is eff, just add it.

Why is this? and is there a better way (read the shorter way)?

+4
source share
4 answers

As in C #, the result of the sum of a byte and a byte in Nemerle is int . However, unlike C #, Nemerle tries to simplify the main language as much as possible by storing all syntactic sugar in the standard macro library. In this spirit, the += and ++ operators are macros that translate into regular additions.

To answer your question, (x + 1) :> byte is a way to do this. This is actually not all bad, because it allows the reader of your code to know what you know about the danger of overflow and be responsible for it.

However, if you really feel it, you can easily write your own macros += and ++ to do the translation. It only takes a few lines of code.

+7
source

Disclaimer: I do not know Nemerle, but I assume that it behaves similarly to C # in this regard.

There is a better and shorter way: do not use bytes.

Why do you use them in the first place? In most cases, computing with int faster than using byte s, because today computers are optimized for them.

+2
source

This is because the CLR only defines a limited number of valid operands for the Add IL command. Valid entries are Int32, Int64, Single, and Double. Also IntPtr, but tends to be disabled in many languages.

Thus, adding a constant to a byte requires the byte to be converted to Int32 first. The result of the addition is Int32. What does not fit in bytes. If you do not use a larger hammer. This is great, the probability that you are overflowing with Byte.MaxValue is quite high.

Please note that there are languages โ€‹โ€‹that are automatically applied, VB.NET is one of them. But it also automatically throws an OverflowException. Obviously not the one you are using, nor C #. This is an ideal choice, the overflow test is not so cheap.

+2
source

This is what the type system does. Adds update values โ€‹โ€‹to int and then performs an operation leading to int. Also thought what should happen if the initial value was 255?

0
source

All Articles