Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split up a long value (32 bits) into four char variables (8bits) using C?

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? 

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

It is little Endian.

ALSO I want CurrentPosition to remain unchanged.

like image 507
PICyourBrain Avatar asked Apr 30 '10 19:04

PICyourBrain


People also ask

How many bits in a long?

The size of the long type is 8 bytes (64 bits).

How many bits is C?

Pointers. The ARMv7-M architecture used in mbed microcontrollers is a 32-bit architecture, so standard C pointers are 32-bits.


2 Answers

    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.
like image 189
nos Avatar answered Oct 21 '22 08:10

nos


I think you should consider using a union:

union {
   unsigned long position;
   unsigned char bytes[4];
} CurrentPosition;

CurrentPosition.position = 7654321;

The bytes can now be accessed as: CurrentPosition.bytes[0], ..., CurrentPosition.bytes[3]

like image 34
Justin Muller Avatar answered Oct 21 '22 07:10

Justin Muller