Multiple var types in char array

Go To Last Post
3 posts / 0 new
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I would like to be able to write/retrieve multiple variable types to/from a character
array. The single byte data is updated/read via a communications routine. I know
that variable type x starts at array index I for any given implementation.

Character data retrieval is, of course, simple. Integers I can construct/ reconstruct from two characters using bit shifting. Longs can be constructed/reconstructed via more bit shifting and with longer data types it gets worse.

I would prefer to not do any bit shifting to keep the code fast and simple. I have considered unions but this would waste a lot of space as each variable would occupy the space of the longest defined type.

The way I am doing this now is to set up an array at an absolute RAM location:

#define MB0 200

#define MB1(addr) (*(volatile unsigned char*)((addr)+MB0))
#define MB1S(addr) (*(volatile signed char*)((addr)+MB0))
// You must disable global interrupts before and re-enable after
// any multibyte Mailbox access to prevent data corruption
#define MB2(addr) (*(volatile signed int*)((addr)+MB0))
#define MB2U(addr) (*(volatile unsigned int*)((addr)+MB0))
#define MB4(addr) (*(volatile signed long*)((addr)+MB0))
#define MB4U(addr) (*(volatile unsigned long*)((addr)+MB0))

I can say:

int int_var;
long long_var;

int_var = MB2(6);
MB2(8) = int_var;
long_var = MB4(10);
MB4(14) = long_var;

This works and gives optimal code, but its not very c friendly and you
must manually locate the array in RAM.

Anyone having any better ideas?

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I don't understand at all what you want, but I use unions in same cases.

union T
int a;
long b;
char c;

char buf[200];

int a = ((T*)buf)->a;
long b = ((T*)buf)->b;

and so one.
Using pointer to union unstead union can save memory space.

admin's test signature

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

This problem was solved using the following method (from a post on the other forum):

char s[20];
*(int *)(&s[8])=10000;
*(long *)(&s[14])=500L;

I have tested this method and it works, producing optimum code.