ACCESS LOW/HIGH BYTES OF A INTEGER VARIABLE

C51: ACCESS LOW/HIGH BYTES OF A INTEGER VARIABLE


Information in this article applies to:

  • C251 Version 3.20
  • C51 Version 6.20

QUESTION

I would like to address the low or high byte of an int variable. Is there a way to access this directly in the C language?

Other compilers offer me macro or intrinsic functions do to that. Why is there no such function in Keil C51?

ANSWER

The C Language allows you to directly access the low or high bytes of an int/unsigned int variable. The Keil C51 Compiler is an optimizing compiler that generates very efficient code for such constructs. Therefore, there is no need for special intrinsic functions.

Following are two solutions to your problem.


The following example uses shift operations to perform byte accesses. This is Standard ANSI C and it may be easily ported to any other microcontroller plattfrom regardless of the byte order (little endian or big endian) in the target hardware.

#define LOWBYTE(v)   ((unsigned char) (v))
#define HIGHBYTE(v)  ((unsigned char) (((unsigned int) (v)) >> 8))

unsigned int  x;
unsigned char cl, ch;

void test (void)  {
  cl = LOWBYTE(x);
  ch = HIGHBYTE(x);
}

The previous example only handles read accesses. If you need write accesses at the byte level, you may use the following pointer definitions. The following example is written for architectures with big endian byte order (like the 8051) and must be adjusted to run on little endian architectures.

#define BYTELOW(v)   (*(((unsigned char *) (&v) + 1)))
#define BYTEHIGH(v)  (*((unsigned char *) (&v)))

void test1 (void)  {
  BYTELOW(x) = BYTEHIGH(x);
  BYTEHIGH (x) = 5;
}

Both program examples generate code that is comparable to assembler programming techniques.

SEE ALSO

FORUM THREADS

The following Discussion Forum threads may provide information related to this topic.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值