Store 4 different values in a byte

前端 未结 3 1413
忘了有多久
忘了有多久 2021-01-25 01:32

I have an assignment to do, but I have no clue where to start. I am not expecting and definitely do not want answers in code. I would like some guidance as in what to do because

相关标签:
3条回答
  • 2021-01-25 01:37

    Here is another way of doing it.

        unsigned int i = 0;
    
        engine_on = 1;
        gear_pos =2;
        key_pos = 2;
        brake1 = 1;
        brake2 = 1;
    
        i |= s1.brake2;
        i |= (s1.brake1 << 1);
        i |= (s1.key_pos << 2);
        i |= (s1.gear_pos << 4);
        i |= (s1.engine_on << 7);
    
    0 讨论(0)
  • 2021-01-25 01:42

    Have you read about bit field?

    struct s {
      unsigned char engine_on : 1;
      unsigned char gear_pos : 3;
      unsigned char key_pos : 2;
      unsigned char brake1 : 1;
      unsigned char brake2 : 1;
    };
    
    0 讨论(0)
  • 2021-01-25 01:48

    lets call a byte b, if you set b to 0, you end up with (binary) 0000 0000 (space for readability)

    Now we want to pack the different parts into this byte

    engine_on  0-1    1
    gear_pos   0-4    3 
    key_pos    0-2    2 
    brake1     0-1    1
    brake2     0-1    1
    

    brake2 is simple. We can just set b to the value of brake2 and we will end up with 0000 0000, or 0000 0001 depending on if it is a 0 or a 1.

    now we want to set brake 1 to b. We can do this by using a or/equal and the number itself but bitshifted to the right position. We end up with the following:

    b |= (brake1 << 1) 
    

    lets explain how I came at this:

    brake1 = 0000 0001 //lets assume its a 1 not a 0)
    (brake1 << 1) = 0000 0010
    b = 0000 0001 //lets assume brake 2 was 1.
    

    to 'add' the value from brake1 to b we have to set each bit if either the bit in b is 1 or if the bit in (brake1 << 1) is one. This is done by a 'bitwise-or', so we end up with:

    b = b | (brake1 << 1) // which can also be written as:
    b |= (brake1 << 1)
    

    now you can also add the other parts, it also works with more bits at the same time. I hope this has been helpful

    0 讨论(0)
提交回复
热议问题