gpt4 book ai didi

c - 如何使用 C 将一个 long 值(32 位)拆分为四个 char 变量(8 位)?

转载 作者:太空狗 更新时间:2023-10-29 16:46:07 24 4
gpt4 key购买 nike

我有一个 32 位长的变量 CurrentPosition,我想将其拆分为 4、8 位字符。我将如何在 C 中最有效地做到这一点?我正在使用 8 位 MCU,8051 架构。

unsigned long CurrentPosition = 7654321;
unsigned char CP1 = 0;
unsigned char CP2 = 0;
unsigned char CP3 = 0;
unsigned char CP4 = 0;
// What do I do next?

我是否应该只用指针引用 CurrentPosition 的起始地址,然后将该地址的 8 加 2 四次?

它是小端。

另外,我希望 CurrentPosition 保持不变。

最佳答案

    CP1 = (CurrentPosition & 0xff000000UL) >> 24;
CP2 = (CurrentPosition & 0x00ff0000UL) >> 16;
CP3 = (CurrentPosition & 0x0000ff00UL) >> 8;
CP4 = (CurrentPosition & 0x000000ffUL) ;

您也可以通过指针访问字节,

unsigned char *p = (unsigned char*)&CurrentPosition;
//use p[0],p[1],p[2],p[3] to access the bytes.

关于c - 如何使用 C 将一个 long 值(32 位)拆分为四个 char 变量(8 位)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2747219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com