Bitwise operation

2

In my first semester of college I made an algorithm to avoid wasting memory, just for testing.

Now I'm passing this code to C:

Here is the whole code:

// 8 bits

// Aguenta até 4 slots (0 - 3)
// Valor inteiro máximo suportado: 255

void setBit8(int *pInt32, int index, int valor)
{
    *pInt32 = (*pInt32 & ~(0xff << index * 8)) ^ (valor << (index * 8));
}

int getBit8(int *pInt32, int index)
{
    return ((*pInt32 >> (index * 8)) & (0xff >> 32));
}

// exemplo de uso:
setBit8(&var, 2, 168);
printf("%d", getBit8(&var, 2)); // imprime 168;

And I get the following warning in the getBit8 function:

  

warning: right shift count >= width of type

The intention is to make the same 4-byte variable can receive up to 4 integer values inside it, being able to access or modify these values, such as an array ...

What is the problem / error?

    
asked by anonymous 16.03.2017 / 17:49

1 answer

3

I do not know if the algorithm does what it wants, or something useful, or if it will save some memory, it does not seem to, but the problem is that potentially the int type can be less than 32 and so a problem may occur . So either you have to use a sizeof(int) to ensure that you use the type size, or use int32_t type that ensures that it is 32 in size, but depending on the compiler and your configuration only the first one will work.

C has minimum size defined and not so much maximum or fixed size, int can be at least 16 bits and should be less than long .

#include <iostream>
using namespace std;

int getBit8(int *pInt32, int index) {
    return (*pInt32 >> (index * 8)) & (0xff >> sizeof(int));
}

int getBit8x(int32_t *pInt32, int index) {
    return (*pInt32 >> (index * 8)) & (0xff >> 32);
}

int main() {
    int a[] = { 0, 1, 2, 3 };
    getBit8(a, 2);
    getBit8x(a, 1);
    printf("%d %d %d %d", a[0], a[1], a[2], a[3]);
}

See running on ideone . And in the Coding Ground that does not allow you to compile the second form. Also I put it in GitHub for future reference .

    
16.03.2017 / 18:12