Bit operation

Asked

Viewed 132 times

2

In my first semester of college I did an algorithm in order to avoid memory waste, just for testing.

Now I’m passing this code to C:

Here’s 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 function getBit8:

warning: right shift count >= width of type

The intention is to make the same variable of 4 bytes can receive up to 4 integer values within it, being able to access or modify these values, as a array...

What is the problem/error?

  • It would be able to provide the code that makes the method call?

  • I’ll edit my question!

1 answer

3


I don’t know if the algorithm does what it wants, or something useful, or if it will save some memory, it doesn’t seem, but the problem is that potentially the type int may be less than 32 and so a problem may occur. Then or have to use a sizeof(int) to ensure that you use the type size, or use the type int32_t which ensures it is 32 in size, but depending on the compiler and its configuration only the first will work.

C has defined minimum size and not so much maximum or fixed size, the int can be at least 16 bits and must be smaller than the 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]);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thank you very much for your attention, I reviewed the code and the error was precisely in this part. Incidentally, this part was really unnecessary... Anyway, thank you very much!

  • @Mateuscosta take a look at the [tour] how to proceed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.