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

  • [email protected]
    April 10th, 2010 at 9:45 am

    I had received an email from a Jim about an error I overlooked when making this entry… a type ‘int’ is only 32 bits, so shifting 40 bits causes grief. Instead use ‘long long int’ which guarantees 64 bits on a 32 bit architecture, and might be 128 bit on a 64 bit machine. I updated the entry appropriately.

Share your thoughts, leave a comment!