View previous topic :: View next topic |
Author |
Message |
kmp84
Joined: 02 Feb 2010 Posts: 354
|
bitwise operation |
Posted: Tue Apr 28, 2015 2:48 am |
|
|
Hi all!
Sorry if the topic is repeated, but which is the simplest way to do this:
I have int16 value for example: 0x1234.
How can I get (make) 4-8bit value : 0x01,0x02,0x03,0x04 ?
Thanks for Attention! |
|
|
ckielstra
Joined: 18 Mar 2004 Posts: 3680 Location: The Netherlands
|
|
Posted: Tue Apr 28, 2015 3:21 am |
|
|
Those units of 4-bits are called 'nibble'. Search the internet and you'll find many answers.
Universal method working on all computers:
Code: | int8 nibble1, nibble2, nibble3, nibble4;
int16 value;
nibble1 = (value >> 12) & 0x0F;
nibble2 = (value >> 8) & 0x0F;
nibble3 = (value >> 4) & 0x0F;
nibble4 = (value >> 0) & 0x0F; |
Depending on your compiler version and processor type it is possible to make this code more efficient, but general rule is to only optimize when you have to. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19539
|
|
Posted: Tue Apr 28, 2015 3:22 am |
|
|
There is simplest, versus quickest.
Simplest, just mask and rotate. Work from the bottom up. So something like:
Code: |
//starting with an int16 value in 'val'
int8 nibbles[4];
int8 ctr=4;
do
{
nibbles[--ctr]=val&0xF;
val/=16;
} while (ctr);
|
Fastest:
Code: |
#define NIBS(x,v) nibbles[x]=v&0xF;swap(v);nibbles[x-1]=v&0xF
//again starting with 'val'
int8 nibbles[4];
int8 part;
part=make8(val,0);
NIBS(3,part);
part=make8(val,1);
NIBS(1,part);
|
The former takes 95 instruction cycles, versus 18 for the second. You can actually speed this slightly further by not having the make8 instructions, instead having a union declared between the bytes and the int16 value. A look at the assembler instructions available on the processor will explain why this latter is so efficient.
It's also worth noting that the compiler knows a lot about these efficiencies, and using the version doing four separate shifts, 'knows' how to save instructions using swap and make8, and in fact codes this down to just 28 instructions. |
|
|
kmp84
Joined: 02 Feb 2010 Posts: 354
|
|
Posted: Tue Apr 28, 2015 5:07 am |
|
|
Thanks "ckielstra" and "Ttelmah" for the detailed explanation! |
|
|
|