Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

123
Visualizações
Right shifting unsigned variables gives strange result - C / GBDK

I'm developing a gameboy game in GBDK but I've got a problem with right-shifting (8bit) unsigned variables. The code looks like this.

#include <gb/gb.h>
#include <stdio.h>

#define GAME_OBJ_MAX_WIDTH 10
#define GAME_OBJ_MAX_HEIGHT 8

struct game_obj
{
    UBYTE matrix[GAME_OBJ_MAX_WIDTH];
    UBYTE width, height;
};

void draw_game_obj(struct game_obj *object)
{
    for (unsigned char i = 0; i < object->width && i < GAME_OBJ_MAX_WIDTH; i++)
   {
       printf("BASE->%d\n", object->matrix[i]);
       for (unsigned char j = 0; j < object->height && j < GAME_OBJ_MAX_HEIGHT; j++)
           printf("Shift by %d->%u\n", j, object->matrix[i] >> j);
   }
}

void main() {
    struct game_obj racer;
    racer.height = 4;
    racer.width = 3;
    racer.matrix[0] = 10;
    racer.matrix[1] = 7;
    racer.matrix[2] = 10;
    draw_game_obj(&racer);
}

The output is:

BASE->10
Shift by 0->235
Shift by 1->117
Shift by 2->58
Shift by 3->29
BASE->7
Shift by 0->235
Shift by 1->117
Shift by 2->58
Shift by 3->29
BASE->10
Shift by 0->235
Shift by 1->117
Shift by 2->58
Shift by 3->29

Basically any unsigned value right shifted (even by 0) changes to 235, 117, 58 and so on... I'm trying to understand why is that.

Solution

Issue fixed by assigning object->matrix[i] to separate variable.

void draw_game_obj(struct game_obj *object)
{
    for (unsigned char i = 0; i < object->width && i < GAME_OBJ_MAX_WIDTH; i++)
   {
       printf("BASE->%d\n", object->matrix[i]);
       UBYTE u = object->matrix[i];
       for (unsigned char j = 0; j < object->height && j < GAME_OBJ_MAX_HEIGHT; j++)
           printf("Shift by %d->%u\n", j, u >> j);
   }
}
over 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda