Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Updating a byte 2

Status
Not open for further replies.

Kocky

Programmer
Oct 23, 2002
357
NL
Hello,

I have a BYTE variable that contains a value.
Example: 0x11
What I want to do is split the high and low nible apart so I get 1 and 1. Then I want to increment the high nible with one and store it in the variable so I'll get 0x21.
How do I do this ? I read something about right shifting (>>) ??

Thanx
 
I am not testing the code below, but mostly it shall work.

unsigned char dojob(unsigned char val)
{
unsigned char temp1 = val & 0x0F; // This extracts right nibble.
unsigned char temp2 = ((val & 0xF0) >> 4); // This extracts right nibble.
unsigned char result;

temp2++; //Increment left nibble

result = temp2; // This will put left nibble in wrong place
result <<= 4; // Bring it back as left nibble

result |= temp1; // Or with the right nibble to create result

return result;
}
 
Why not just add 0x10? This won't (can't!) affect the low nibble in any way, but will add 1 to the high nibble.

 
Thanx guys !
I'm now using 0x10 to increment the left nible and 0x01 to increment the right nible.

If I want to know the value of the left nibble I use
temp = val >> 4
And for the value of the right nible I use
temp = val & 0x0F

A star for you both !
 
... but just remember that if you increment the right nibble by adding 0x01, it will carry over into the left nibble if it was already 0x0F. To avoid this you could mask the original left nibble by & 0xF0, mask the incremented right nibble with 0x0F (as you already do), and or the two masked nibbles together. This will preserve the original high nibble while the low nibble cycles back from F to 0.
Thanks for the star!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top