Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

122
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda