Convert Small Array to Single Variable and Back Again

Here is a method that will allow you to essentially merge elements of an array into a single variable and then back again in c.

unsigned char mac_addr[6];
long long int x;

x = mac_addr[0] << 40;
x |= mac_addr[1] << 32;
x |= mac_addr[2] << 24;
x |= mac_addr[3] << 16;
x |= mac_addr[4] << 8;
x |= mac_addr[5];

mac_addr[0] = x >> 40;
mac_addr[1] = x >> 32;
mac_addr[2] = x >> 24;
mac_addr[3] = x >> 16;
mac_addr[4] = x >> 8;
mac_addr[5] = x;

You could probably take it a step further and throw it into a loop of sorts. If you have another solution, feel free to share it in the comments below!

Feel free to donate if this post prevented any headaches! Another way to show your appreciation is to take a gander at these relative ads that you may be interested in:

There's 1 Comment So Far

Share your thoughts, leave a comment!