Right shifting unsigned variables gives strange result - C / GBDK

111 views Asked by At

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);
   }
}
0

There are 0 answers