Home > Software engineering >  Bitwise operation aren't making any sense
Bitwise operation aren't making any sense

Time:12-23

my current understanding of bitwise operations is that it would push the binary reprisentation of a number a specific amount of times either removing numbers in the process (in case of >>) or add 0's in the end of a number (in case of <<). so why is it so when i have a int32 storing a hex value of int32_t color = 0xFFFF99FF; (= 1111 1111 1111 1111 1001 1001 1111 1111) bitshifting right this int by 24 should give the value FF , because we moved the first two byts by the number of the byts remaining (32 - 8 = 24) but what actually happens is that i end up with the value -1 when i execute my code and 0 in calculator note : bitshifting right by 18 yeilds me the desired result.

am using the SDL2 library and C

am trying to store colors as their hex values then extract the red,green and blue chanel ignoring the alpha one . the code here is minimized without any unacessary details.

int32_t color; //hex value of the color yellow


//taking input and changing the value of color based on it

if (event->type == SDL_KEYDOWN) {
    switch (event->key.keysym.sym)
    {
        case SDLK_a:
            //SDL_SetRenderDrawColor(renderer, 255, 255, 153, 255); // sand 
            color = 0xFFFF99FF; //hex code for sand color 
            break;
        case SDLK_z:
            //SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255); // water
            color = 0x0000FFFF; //hex code for blue color ...
            break;
        case SDLK_e:
            //SDL_SetRenderDrawColor(renderer, 139, 69, 19, 255); // dirt
            color = 0x8B4513FF;
            break;
        case SDLK_d:
            //SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // delete button || air
            color = 0x000000FF;
            break;
        default:
            OutputDebugString("unhandled input.\n");
            break;
    }
}

//checking for mouse input and drawing a pixel with a specific color based on it
if (event-\>button.button == SDL_BUTTON_LEFT)
{
        SDL_SetRenderDrawColor(renderer, color \>\> 24, (color \>\> 16) - (color \>\> 24), (color \>\> 8) - ((color \>\> 16) - (color \>\> 24)   color \>\> 24));
        OutputDebugString(std::to_string(color \>\> 24).c_str());
        SDL_RenderDrawPoint(renderer, mouseX / 4, mouseY / 4);
        SDL_RenderPresent(renderer);
}

CodePudding user response:

int32_t is signed and then >> is the signed shift, keeping the sign bit 31. You should use uint32_t. And it also is more logical to use uint8_t for color components.

  • Related