Search code examples
c#unity-game-enginebooleanbit

Any way to force value of bool to read as -1/1 instead of 0/1?


I've been using an int in my code to define a horizontal direction. This is so I could use it in my movement code (eg. position.x += speed * direction). Before this I had been using a bool, but that needed if statement to see if speed was a pos/neg value.

But I was just thinking, well this uses now a byte (or 4 in my instance, Unity int32) rather than just one bit.

I know you can cast a bool to int for example but is there a way to store my direction value and use it in the formula like above but only being one bit?

I am using Unity and C#. I realise this is not very important, but just trying to learn if this possible or not.


Solution

  • Note that modern machines fetch the data as a block of bytes called word, it may be 4 bytes or 8 bytes depending on the architecture.

    You can store one bit of information by bit-wise operators but it can only be useful if you multiple bits to pack into one word or byte.

    So, if you want to store the direction as a boolean (1 bit of information) then you will have to use if-else statements. Otherwise, you can't represent the sign as well as the absolute value in just one bit!