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

后端 未结 6 1865
我寻月下人不归
我寻月下人不归 2020-12-29 11:04

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, 80

6条回答
  •  一生所求
    2020-12-29 11:22

    I know this was posted some time ago. But for anyone still reading the thread: Many people take the approach of sequentially shifting the original value. Why not let the compiler do the work for you. Use a union & to allow you to store the values in the same location. Define a union consisting of both a 32 bit long variable (this will be where you save your CurrentPosition) and a structure consisting of 4 char variables. Or just a simple 8 bit integer array. When you write your CurrentPosition to the long variable, it will be stored in the same location accessed when you read the 4 char variables. This method is much less labour intensive and does not allows the compiler to do the work instead of wasting time & resources.

提交回复
热议问题