Hexadecimal math or bits?

I have a variable sequence of values from a canbus, these are markers, and for error detecting.

Basic sequence in hexadecimal is;
20 to 2F repeating,
there are markers within, if the packet contains the first byte intended for use as ASCII, 25 would become 5 or 2C would be C.
The end marker is 15 where a normal msg is 25.

I wrote some instructions to predict the next value in the chain if it is the last:
21 /1, next val, if last = 12
2C /C, next val, if last = 1D etc

until I get 2F and predict my end msg as 20 instead of 10, I know I can if() my way out of these quirks but...

It looks like I should be doing something with the bits/bytes and not using decimal math.

Norm. ASCIIstart Predict end val
0010 0001/0000 0001 = 0001 0010
0010 1111/0000 1111 = 0001 0000

Not a clue where to start in code, names and pointers please :slight_smile:

The underlying bits/bytes are the same no matter how you represent the number, so I can't see that it makes any difference from that perspective.

If the protocol is specified in terms of hex values then it is usually easier to use the same base when coding as you get a 1-1 correspondence with what is in the spec.

I think I need to know how to turn the byte into two separate values, nibbles??? Or treat the byte in a way that only reads the first four or last four bits??
Nibble A and Nibble B.
That way when I send or receive I can use Nibble B for missing message checks and next message ID in sequence for send and then Nibble A is either Std msg, Contains ASCII or Last msg in chain.
Ie Nibble B = 0000/0001/0010/0011/0100/0101/0110/0111/1000/1001/1010/1011/1100/1101/1110/1111 (message sequence iD)
Nibble A = 0010/0000/0001 (message type).

I think my first approach of doing math on it is just wrong,
Norm msg
2A-0F=1B, correct
20-0F=11, correct
ASCI msg
0E+11=1F, correct
07+11=18, correct

2F and 0F give results that don’t account for the loop returning to 0.

For now I’ve just written if()s that account for it but when I get to sending messages I’d like to be able to treat one Byte as two separate values and then combine them before I send my message out onto the CAN network.
I realise I could just have two separate bytes and then add them pre send but I’m essentially wasting 50% of my memory doing so.

Ideas/thoughts appreciated :slight_smile:

Sounds like you need to find out about “bitwise operators” &, |, >>, << etc.

& is a logical and operation on the bits (0xa5 & 0xf = 0x5)
| is logical or (0xa0 | 0x5 = 0xa5)

and << are a shift in the direction they point in ((0xa5 & 0xf) >> 4 = 0xa)

That looks like exactly what I need thank you!

uint8_t theByte = 0x3D;
uint8_t msNibble = theByte >> 4;
uint8_t lsNibble = theByte & 0xF;

Will result in 0x3 and 0xD for most significant nibble and least significant nibble.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.