Bit ...

Discussion in 'Teaching Programming with B4X' started by ilan, Apr 2, 2017.

  1. ilan

    ilan Expert Licensed User


    Can someone please explain what does bit.shiftlet, bit.and, bit.or,..

    How can we use it and in what cases do we use them.

    The reason i ask is i try to learn Spritekit and @JanPRO have provided 2 examples. (Flappy bird and brick)

    Now in flappy bird i see that he is declaring the collisions categories as int so you can set what body will collide with what category but he is doing it like this:

    Private category_bird as int
    Private category_world as int
    Category_bird = bit.shiftleft(1,0)
    Category_world = 
    Why using bit.shiftleft and not give it a number like 1,2,3,....?

    I dust dont understand the use of bit.x can someone please explain.

    Thank you :)
    Last edited: Apr 2, 2017
  2. stevel05

    stevel05 Expert Licensed User

    ilan likes this.
  3. ilan

    ilan Expert Licensed User

    Ok thanks @stevel05

    But i still have a question

    Bit.shiftleft(1,0) will return 1
    Bit.shiftleft(1,1) will return 2
    Bit.shiftlwft(1,2) will return 4

    So why not just write

    Category_bird = 1

    Is there any benefit in using bit instead of writing the number you want?
    Last edited: Apr 3, 2017
  4. stevel05

    stevel05 Expert Licensed User

    You can store more than 1 value in the int, in the case of booleans you can use each bit as a separate flag, so rather than using 32 boolean variables as flags, you could store them all in 1 int and access then with the Bit operator.
  5. ilan

    ilan Expert Licensed User

    Thank you. I still need to understand where and how it can be used and where it is a better choice then an int and yours answers are a very good start for that :)
  6. canalrun

    canalrun Well-Known Member Licensed User

    I think that bit operations were more useful in the olden days before there was tons of memory and powerful CPUs. I think it's best to think in terms of binary when using bit operations. When math operations were slow it used to be handy to use a right shift by one bit to divide by two and a left shift by one bit to multiply by two. You can also accomplish non-powers of two by shifting and adding back the original number in various combinations.

    Another useful use for binary numbers and shift operations was implementing a state machine – especially long before there were CPUs. You could just have a shift register and use the resulting bit pattern to control your state. Think of a traffic light. If you just shift the bit in a register by one position every 15 seconds and use the resulting bit pattern to control the red, yellow, or green light, you have a very simple state machine.

    When looking at the Android documentation for certain functions (camera parameters for example), they use values to represent parameters that are essentially 1's in certain bit positions of an integer.

    From the documentation:
    ShiftLeft (N As Int, Shift As Int) As Int
    Shifts N left.
    Shift - Number of positions to shift.
    ShiftRight (N As Int, Shift As Int) As Int
    Shifts N right.
    Keeps the original value sign
    Shift - Number of positions to shift.

    I'm not familiar with the code that is referenced, but he may be using shift operations for some kind of implementation of a "state" machine.

    I personally think it's easier and more intuitive to use full-length Boolean, integer, or enum variables to accomplish this.

  7. freedom2000

    freedom2000 Well-Known Member Licensed User

    Bit operators are still commonly used with Microcontrolers where memory is not big...
    One 8 bits words = 8 states of 8 buttons for example
    fireday, lemonisdead and JordiCP like this.
  8. sorex

    sorex Expert Licensed User

    For some people it easier to roll a bit a few times instead of using the right value. most programmers know that these are 2^n variants tho and know them out of their head.
  9. wonder

    wonder Expert Licensed User

    @ilan, for example bitmap operations:
    unsigned long createRGB(int r, int g, int b)
    return ((r & 0xff) << 16) + ((g & 0xff) << 8) + (b & 0xff);

    Input: createRGB(162, 30, 164)
    Output: 0xA21EA4
    ilan, inakigarm and Cableguy like this.
  10. melonZgz

    melonZgz Active Member Licensed User

    I use a lot of bitwise operators when programming microcontrollers. You have to, to configure registers, to read inputs, to manage outputs, to store booleans (in one byte you can store 8 booleans)... but I think I've never used any of them with b4x...
  11. RandomCoder

    RandomCoder Well-Known Member Licensed User

    Bit shift left and bit shift right is still used a lot within industrial control systems. A very simple example would be part tracking on a conveyor where the shift occurs with every pulse of the encoder and a 1 is set when a part is loaded. The 1 then shifts with each pulse of the encoder until the desired bit position which might trigger a reject sequence or the next operation.
    Bit shifting is also good for storing or buffering parts. If a process is unable to accept a component you might want to buffer it i.e. bit shift left a value of 1 and continue doing this as each new part arrives. Once the process is ready to accept parts again you simply bit shift right and unload all the 1's until there are no more.
    Maybe you have heard of terms such as FIFO and FILO, first-in-first-out and first-in-last-out? These were typically associated with bit shift operations.
  12. sorex

    sorex Expert Licensed User

    if you want to try some retro coding (c64, speccy whatever) then prepare for a lot of that stuff. :)

    memory was limited so for example all gfx data (bitmaps, charsets, sprites) are based on bit settings inside bytes.
    for example 8 hires pixels is 1 byte (1 bit/pixel). 4 multi color pixels is also 1 byte (2 bits/pixel).

    so people who coded back then still think like that and it's a good way to optimize game data aswell.
    Peter Simpson and wonder like this.
  13. ThRuST

    ThRuST Well-Known Member Licensed User

    A bit late, but I just have to contribute to this by recommending this site for Retro programming techniques. Have a look >here<
  14. MaFu

    MaFu Well-Known Member Licensed User

    Not to forget the performance benefit. If i divide/multiply a integer value by 2/4/8/... i can also use bit shifting. In languages like C or Pascal, where the bit shift commands are operators, shifting is much faster than multiply or divide. This is not the case in B4X.
    RandomCoder likes this.
  15. udg

    udg Expert Licensed User

    Another possible use is when you want to code multiple roles (or rights) for a user.
    Read-only, Write/read, Insert, Delete.. each one could be a bit set to 1 or 0 so a single byte/word can completely defines ones rigths.
    Programmer, Project Manager, Project Leader are examples of not mutually-exclusive roles a specific user could be entitled for a project.
    Winter, Spring, Summer, Autumn could be combined to show in which season(s) a given food is available during the year.
    And so on..
  16. ThRuST

    ThRuST Well-Known Member Licensed User

    udg, how would you put this in code? would be nice to see a short code example
  17. udg

    udg Expert Licensed User

    Let me look for an old proof-of-concept using seasons and I'll post some code.
    ThRuST likes this.
  18. udg

    udg Expert Licensed User

    Well, it's taking too long to find that code, so I try to reproduce part of it right here. Please, consider it as a schematic explanation rather than ready to use code.
    'Constants to make code more readable. We don't strictly need them
    Dim const Winter as byte = 1  '...0001
    Dim const Spring as byte = 2  '..0010
    Dim const Summer as byte = 4 '..0100
    Dim const Autumn as byte = 8  '...1000

    'Set Pizza as always available
    Pizza = 15 'i.e all bits set

    'Test if Pizza is available in Summer
    log (Bit.and(Pizza,Summer) = Summer)  ' --> 15 AND 4 = 4, third bit from right is set? YES

    'Set Watermelon as available only in Summer
    Watermelon = 4 'i.e Summer only

    'Test if Watermelon is available in Summer
    log (Bit.and(Watermelon ,Summer) = Summer) '--> 4 AND 4 = 4? YES

    'Test if Watermelon is available in Winter
    log (Bit.and(Watermelon ,Winter) = Winter) '--> 4 AND 1 = 1? NO

    'Set ABC for Spring and Summer
    dim abc as byte = 0
    abc = 
    Bit.Or(Bit.Or(abc, 4),2)  'abc = 6; 0110
    This should give you a rough idea. Now it's lunch time for me..and I have no pizza ready..sigh!
  19. ThRuST

    ThRuST Well-Known Member Licensed User

    yea we can't eat pizza everyday that's for sure :) Interesting solution this will be fun to play around with.
    Those bits truly share an important piece of history. Little did we know that storage space would come to be so cheap
    that bit rotation simple would not be an option any longer. But old-school programmers know they meant everything back in the days
    I still remember, when Bit shifting rocked hard :cool: Wrap
  20. Beja

    Beja Expert Licensed User

    Hi Ilan,
    I will try to answer your question from electronics viewpoint.. I think it will give better and more clear picture then can be easily used in software.
    In microprocessor registers, shift and rotate commands work on bytes, words and long words.
    1. Byte = 8 bits (duh)
    2. Word = 16 bits
    3. Ling word = 4 bytes or 32 bits.

    4. Rotate left holds the 8 bits binary value as is and rotate them to the left.. E.g. if you have the byte:
    1010 1011 the after the command rotate left you will have:
    0101 0111
    You can see the left most bit appeared back on the right side. Becuase you rotated the byte.
    But if you executed the shift left command then the new value of the above byte will be:
    010 10110
    The left most bit is lost, because you shifted the byte and didn't rotate them.

    XOR (exclusive OR)
    Let's start with examples!
    1 XOR 1 = 0
    1 XOR 0 = 1
    0 XOR 1 = 1
    0 XOR 0 = 0

    You can see that the two compared values MUST have different values in order for the result to be 1.
    XOR is normally used when you want to make a picture transparent. In this case you XOR all the picture pixels with that of the background. Or if you want to cancel a specific color..etc.

    The AND operator gives you 1 IF the values of both compared bits are 1, it will give 0 for all other combinations..

    Sorry for the poor explanation.
    jimmyF and JanPRO like this.
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice