Char array to unsigned long, byte shifting problem

I am running into problems when trying to create an unsigned long from char array. The routine is needed for populating time data from NTP server response using the ethernet UDP library. The network segment of the code returns the correct buffer and the bytes are (from the application log):
byte #1 = 00D2, byte #2 = 00E0, byte #3 = 00AA, byte #4 = 007F

the shifting routine is:

unsigned long ulong = ((unsigned long) b1) << 24;
ulong |= ((unsigned long) b2) << 16;
ulong |= ((unsigned long) b3) << 8;
ulong |= ((unsigned long) b4);
sprintf(logbuffer, “ntp result: %08X”, ulong);
logData(logbuffer);

The output of the log file that contains the buffer filled out with sprintf: “ntp result: 0000AA7F”.

The result indicates that byte #1 (b1) and byte #2 (b2) are not in the unsigned long.

I have tried to fill the unsigned long with adding the bytes with mask which should produce the same result as the above byte shifting:

unsigned long ulong = ((unsigned long)b1 & 0xFF) << 24;
ulong += ((unsigned long)b2 & 0xFF) << 16;
ulong += ((unsigned long)b3 & 0xFF) << 8;
ulong += ((unsigned long)b4 & 0xFF) << 0;

as well as rtying to use all byte shifting routine that known to mankind … even I have tried to check what is happening using memcpy to fill out the unsigned long. All produces the same result, the first two bytes are basically ignored.

Finally, in order to verify what is happening I tried:

const char* hexstr1 = “D2E0A1CF”;
int hex1 = 0;
sscanf(hexstr1, “%X”, &hex1);
sprintf(logbuffer, “hexstr1 %s = %08X\n”, hexstr1, hex1);
logData(logbuffer);

The log data output is: “test hexstr1 D2E0A1CF = 0000A1CF”

again, the first two bytes are ignored.

After this verification I have no idea what is happening :)))) Any help would be appreciated.

I think its the call to sprintf that's failing - %lx might cure this.

MarkT: I think its the call to sprintf that's failing - %lx might cure this.

Indeed that was the problem. Thank you for pointing out.