2

In Jal, it's possible to do something like this:

var word the_var = 0x1234
var byte the_array[2] at the_var;

Now you can easily access the bytes of the word the_var with the_array[0] (0x34) and the_array[1] (0x12). Can something similar be done with the C18 compiler?

I have an unsigned int the_var and want to access the separate chars in that variable using an array.

2 Answers2

4

One C equivalent is to use a anonymous union, there are a few ways to use them so it's worth researching them further but an example is:

static union {
  word the_var;
  byte the_array[2];
};
the_var = 0x1234;
some_value = the_array[0];
some_other_value = the_array[1];

Another way to go about it is to use a pointer to the value:

word the_var = 0x1234;
byte *the_array = (byte *) &the_var;
some_value = the_array[0];
some_other_value = the_array[1];
PeterJ
  • 17,131
  • 37
  • 56
  • 91
3

In C, you can always get a pointer to the data structure and cast it to some other type (such as uint8_t, like this:

long myLong = 123456;
uint8_t* bytePtr = (uint8_t*)(&myLong);
uint8_t seventByte = bytePtr[6];

The first line is your non-byte data, of type long in this case. The second line declares a byte pointer (essentially the same as an array in C) to the same data by taking the address of the data, casting it to a uint8_t pointer, and assigning that to bytePtr which is a pointer to byte(s). The third line exploits the fact that pointers and arrays are almost the same thing in C and treats our bytePtr as an array, so we get the seventh byte out of it via the bracked notation.

angelatlarge
  • 3,611
  • 22
  • 37