0

Say you have a byte variable, and you assign it the decimal value of 102. (byte myByteVariable = 102;) Why is that possible? Shouldn't you have to provide an actual 8 bit value instead to avoid confusion? And how do I set a byte value by supplying bits instead?

Tim
  • 13
  • 5

3 Answers3

2

byte is a decimal type which represents a decimal number, it doesn't represent a bit field. So 102 is a normal value for it, because it's in the range of byte values (which is [0;255]). If you want to manipulate the bits, consider using BitArray or BitVector32.

Eldar Dordzhiev
  • 5,105
  • 2
  • 22
  • 26
2

And how do I set a byte value by supplying bits instead?

If you are setting the byte value explicitly, you can do so using the prefix 0x to indicate that you are doing so in hexadecimal, as an encoding for groups of 4 bits. E.g. the hex value of decimal 102 is 0x66, which is equivalent to 0110 0110.

But for supplying bits directly, Marc Gravell provides an option here for converting from binary to int using the Convert class, and similarly you can convert the string representation of a binary value into a byte using the Convert.ToByte method as:

byte b = Convert.ToByte("01100110", 2);

Community
  • 1
  • 1
khargoosh
  • 1,450
  • 15
  • 40
  • Nice solution, I didn't know about ToByte – Cyral Sep 14 '15 at 00:22
  • According to [MSDN](https://msdn.microsoft.com/en-us/library/system.convert), "A conversion method exists to convert every base type to every other base type." Not all conversions are supported though and some attempts will throw exceptions. – khargoosh Sep 14 '15 at 00:46
1

A byte can store 8 bits (that is values from 0 to 255). A short stores 16 bits, an int 32, etc. Each integer type in C# simply allows the storage of a wider range of numbers. C# allows you to assign a whole number to any of these types.

In order to set each bit individually, you will need to use bitwise operators.

I actually wrote a library a while ago to handle this, allowing you to set each bit of the byte using data[x]. It is very similar to the BitArray class (which I'm not sure if I knew about when I made it)

The main idea of it is:

private byte data;

public void SetBit(int index, bool value)
{
    if (value)
        data = (byte)(data | (1 << index));
    else
        data = (byte)(data & ~(1 << index));
}

public bool GetBit(int index)
{
    return ((data & (1 << index)) != 0);
}
Cyral
  • 13,999
  • 6
  • 50
  • 90