Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# int byte conversion [duplicate]

Tags:

c#

int

byte

Why is

byte someVar; someVar -= 3;  

valid but

byte someVar; someVar = someVar - 3; 

isnt?

like image 907
Dested Avatar asked Sep 04 '10 07:09

Dested


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is C full form?

History: The name C is derived from an earlier programming language called BCPL (Basic Combined Programming Language). BCPL had another language based on it called B: the first letter in BCPL.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.


1 Answers

Surprisingly, when you perform operations on bytes the computations will be done using int values, with the bytes implicitly cast to (int) first. This is true for shorts as well, and similarly floats are up-converted to double when doing floating-point arithmetic.

The second snippet is equivalent to:

byte someVar; someVar = (int) someVar - 3; 

Because of this you must cast the result back to (byte) to get the compiler to accept the assignment.

someVar = (byte) (someVar - 3); 
like image 135
John Kugelman Avatar answered Nov 03 '22 19:11

John Kugelman