Go Down

### Topic: Bit manipulation and addition? (Read 1 time)previous topic - next topic

#### pyrohaz

##### Feb 20, 2013, 01:57 am
Hey guys,
I have two 4 bit numbers but I want to "combine" (lack of a better word) these into one 8 bit

For example:
firstnumber = 1010
secondnumber = 1100

I want to put these together literally like:
10101100

How do I do this?

And also, if I and that 8 bit number with 15, will I get the firstnumber? And therefore anding with 240, get the second number?

Cheers, Harris

#### holmes4

#1
##### Feb 20, 2013, 02:00 am
first number*8+second number

Mark

#### zeb99

#2
##### Feb 20, 2013, 02:13 am
Actually, it would be firstnumber * 16 + secondnumber.

Although this may be more reliable:

result = (firstnumber & 0x0f) << 4 | (secondnumber & 0x0f)

Therefore:

secondnumber = result & 0x0f

firstnumber = (result & 0xf0) >> 4

#### pyrohaz

#3
##### Feb 20, 2013, 02:15 am
I tried Marks method and was wondering why it didnt seem to work, I then tried your method zeb and it worked great! Thanks a bunch as per guys

#### retrolefty

#4
##### Feb 20, 2013, 02:17 am

Actually, it would be firstnumber * 16 + secondnumber.

Although this may be more reliable:

result = (firstnumber & 0x0f) << 4 | (secondnumber & 0x0f)

Therefore:

secondnumber = result & 0x0f

firstnumber = (result & 0xf0) >> 4

Now that is a complete answer. C can be so nice and concise if you let it be.

Mark meant well, just having a bad hair day.

Lefty

#### pyrohaz

#5
##### Feb 20, 2013, 02:28 am

Actually, it would be firstnumber * 16 + secondnumber.

Although this may be more reliable:

result = (firstnumber & 0x0f) << 4 | (secondnumber & 0x0f)

Therefore:

secondnumber = result & 0x0f

firstnumber = (result & 0xf0) >> 4

Now that is a complete answer. C can be so nice and concise if you let it be.

Mark meant well, just having a bad hair day.

Lefty

No need to worry! I definitely appreciate the help from both

#### zeb99

#6
##### Feb 20, 2013, 02:48 am
Glad to have been of assistance.

#### holmes4

#7
##### Feb 20, 2013, 02:02 pm
Opps, It was the red wine

Mark

Go Up