Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

121
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!