-2

I am getting following Error. I tried all types of typecasting but no help. Please let me know what is going on here.

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

byte[] bitVector = new byte[UInt32.MaxValue/8];

//bitVector[((UInt32)x/8)]  |=  (1 << ((int)(x % 8))); ERROR 
//bitVector[((UInt32)x / 8)] |= (1 << Convert.ToByte(x % 8)); ERROR
bitVector[((UInt32)x/8)]  |=  (1 << 5); //No Error
  • What is definition of bitVector array – Mrinal Kamboj Apr 06 '16 at 06:28
  • @Mrinal Kamboj I edited my question. It is Byte[] – user3604557 Apr 06 '16 at 06:56
  • Almost duplicate - http://stackoverflow.com/questions/4123788/whats-wrong-with-this-expression-cannot-implicitly-convert-type-int-to-byte, feel free to find exact duplicate that explains types accepted/returned by shift operators (hint: byte is not one of those). Note that rules for compile time constants are different and would be covered by some other duplicate (for your last line of sample). – Alexei Levenkov Apr 06 '16 at 07:06

2 Answers2

1

Following shall help

bitVector[((UInt32)x/8)]  |=  (byte)(1 << x % 8)

Result of the bit operation is integer and you are trying to fill it in byte type, therefore it needs an explicit typecast

Mrinal Kamboj
  • 11,300
  • 5
  • 40
  • 74
0

You need to use this

bitVector[((UInt32)x / 8)] |= ((byte)1 << (1 % 8));

The two that are giving you trouble are doing so because you are trying assign an int (the result of the byte shift) to a byte array, by forcing the constant that you are shifting to a byte you'll get the expected result.

Zalomon
  • 553
  • 4
  • 14
  • Thanks for responding. I still get the error as soon as I use this (x % 8). Note that I want (x % 8), not (1 % 8) – user3604557 Apr 06 '16 at 06:48