Miral Gandhi
Miral Gandhi

Reputation: 37

What does setting a global variable equal to "0x0" do in C?

I am currently going over some code that is written in C for a microcontroller and I am just trying to figure out why some of the variable are set equal to 0x0 and 0x1. Can someone explain what that does?

Here's the code:

// Global variables
static bool volatile radio_busy;
int xx = 0x0;
int yy = 0x0;
int zz = 0x1;
bool flag = 1;

Upvotes: 1

Views: 721

Answers (1)

paxdiablo
paxdiablo

Reputation: 881973

0x is simply the prefix for hexadecimal numbers (base 16) rather than the default decimal (base 10).

So the array {0x0, 0x1, 0xf, 0x42} consists of the decimal values 0, 1, 15 (because the digits are 0-9, and a-f equating to 10-15) and 66 (from 4 * 16 + 2).

People will often use hexadecimal when the intent is to operate on bit patterns rather than values (since one hexadecimal digit is fully contained within four bits) (a).

The intent is not clear from the snippet you've given - it has annoyingly generic variable names which seem to give no meaningful indication as to what they're used for, something that's a hallmark of untrained programmers who seem to think large variable names somehow take up more space :-)


(a) For example, you might want to do the following to set bit b5 (where bits are numbered from most significant b7 to least significant b0) of a memory mapped location to 1:

unsigned char *memLoc = 0xff00; // memory to modify.
unsigned char curr = *memLoc;   // get current.
curr = curr | 0x20;             // set ONLY b5, or with binary 00100000
*memLoc = curr                  // write it back.

Upvotes: 5

Related Questions