本文介绍了如何使用C将长值(32位)拆分为四个字符变量(8位)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a 32 bit long variable, CurrentPosition, that I want to split up into 4, 8bit characters. How would I do that most efficiently in C? I am working with an 8bit MCU, 8051 architectecture.

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个地址四次?

Should I just reference the starting address of CurrentPosition with a pointer and then add 8 two that address four times?

这是一个小的Endian。

It is little Endian.

我想要CurrentPosition保持不变。

ALSO I want CurrentPosition to remain unchanged.

推荐答案

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

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

You could access the bytes through a pointer as well,

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

这篇关于如何使用C将长值(32位)拆分为四个字符变量(8位)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 08:22