How to extract data from unsigned long variable

My project reads data from a Can_Bus with the MCP2515 board. I have used other’s libraries to read the messages which are stored in an array/struct. I can read and print the message ID and the data payload, but the ID is a 4byte variable (unsigned long 32) which contains hex info from the full ID. I want to extract the 2nd and 3rd bytes for further processing and ignore the 1st and 4th.

e.g. if the message data is 8DF50B73

I want to extract F50B for further processing.

Can someone advise what functions I can use for this process?

Please be gentle, I am in-experienced with C/C++. My previous coding many years ago was in Basic!

Thanks in anticipation.

take a view here.

See this example of decoding OBD data
#include "SafeString.h" from the library manager

int convertToInt(char* dataFrame, size_t offset, size_t numberBytes) {
  // define a local SafeString on the stack for this method
  cSFP(frame, dataFrame);
  cSF(hexSubString, frame.capacity()); // allow for taking entire frame as a substring
  frame.substring(hexSubString, offset, offset + (numberBytes * 2)); // endIdx in exclusive in SafeString V2+
  hexSubString.debug(F(" hex number "));
  long num = 0;
  if (!hexSubString.hexToLong(num)) {
    hexSubString.debug(F(" invalid hex number "));
  return num;


Right shift by 8 and mask with 0xFFFF

( 0x8DF50B73 >> 8 ) & 0xFFFF = 0xF50B

>> 8
 = 0x008DF50B
 & 0x0000FFFF
 = 0x0000F50B
1 Like

Thanks guix, you guided me to the solution.

Thanks also to the others who responded. I learned from your ideas too.