Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# numeric constants

Tags:

c#

casting

I have the following C# code:

byte rule = 0;
...
rule = rule | 0x80;

which produces the error:

Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)

[Update: first version of the question was wrong ... I misread the compiler output]

Adding the cast doesn't fix the problem:

rule = rule | (byte) 0x80;

I need to write it as:

rule |= 0x80;

Which just seems weird. Why is the |= operator any different to the | operator?

Is there any other way of telling the compiler to treat the constant as a byte?


@ Giovanni Galbo : yes and no. The code is dealing with the programming of the flash memory in an external device, and logically represents a single byte of memory. I could cast it later, but this seemed more obvious. I guess my C heritage is showing through too much!

@ Jonathon Holland : the 'as' syntax looks neater but unfortunately doesn't appear to work ... it produces:

The as operator must be used with a reference type or nullable type ('byte' is a non-nullable value type)

like image 601
Rob Walker Avatar asked Sep 04 '08 01:09

Rob Walker


People also ask

Bahasa C digunakan untuk apa?

Meskipun C dibuat untuk memprogram sistem dan jaringan komputer namun bahasa ini juga sering digunakan dalam mengembangkan software aplikasi. C juga banyak dipakai oleh berbagai jenis platform sistem operasi dan arsitektur komputer, bahkan terdapat beberepa compiler yang sangat populer telah tersedia.

C dalam Latin berapa?

C adalah huruf ketiga dalam alfabet Latin. Dalam bahasa Indonesia, huruf ini disebut ce (dibaca [tʃe]).

Bahasa C dibuat pertama kali oleh siapa dan tahun berapa?

Bahasa pemrograman C ini dikembangkan antara tahun 1969 – 1972 oleh Dennis Ritchie. Yang kemudian dipakai untuk menulis ulang sistem operasi UNIX. Selain untuk mengembangkan UNIX, bahasa C juga dirilis sebagai bahasa pemrograman umum.


2 Answers

C# does not have a literal suffix for byte. u = uint, l = long, ul = ulong, f = float, m = decimal, but no byte. You have to cast it.

like image 128
Eric Z Beard Avatar answered Oct 05 '22 13:10

Eric Z Beard


This works:

rule = (byte)(rule | 0x80);

Apparently the expression 'rule | 0x80' returns an int even if you define 0x80 as 'const byte 0x80'.

like image 34
jmatthias Avatar answered Oct 05 '22 12:10

jmatthias