Reputation: 13
I'm transcoding a Delphi App to C++ and got a problem to get the correct way to do the cases of packet headers in C++.
The Headers Comes as "Dword" in a UCHAR buf and i dont want make like: if (packet[0] == 0xFF && packet[1] == 0xFF...);
Ex: Delphi Working with switch case:
case PDword(@Packet[6])^ of
$68FB0200:
begin
//Dword match correctly
End;
end;
is there a way to do the same in C++ like the Delphi Example?
Already checked for some methds but ever fails the comparsion.
UCHAR *Packet ;
Packet = ParsePacket(buf->Buf, buf->Size);
// The ParsePacket Returns FB 00 00 00 78 00 01 F3 02 FD
DWORD Op1 = 0x01F302FD;
DWORD *p_dw = (DWORD*) Packet[6];
if (p_dw == Op1)
{
//Dword never match...
}
Upvotes: 1
Views: 517
Reputation: 35164
The obvious issue with DWORD *p_dw = (DWORD*) Packet[6]
is that you take a value as an address. You probably meant DWORD *p_dw = (DWORD*)&(Packet[6])
.
Note, however, that you get additional troubles for two reasons:
First, alignment could be wrong such that the pointer received is not a valid address to be taken for dereferencing a DWORD. This is undefined behaviour then.
Second, you depend on a specific endianess.
To overcome the first issue, you could use memcpy
:
DWORD Op2 = 0;
memcpy(&Op2,Packet+6,sizeof(Op2));
To overcome both the first and the second issue, you'll need to sum the bytes on your own, e.g.:
DWORD Op2 = Packet[6]<<24 | Packet[7]<<16 | Packet[8]<<8 | Packet[9]
Upvotes: 0
Reputation: 283793
Yes, the portable C (and C++) way is:
DWORD const Op1 = 0x01F302FD;
if (0 == memcmp(Packet + 6, &Op1, sizeof Op1)) { ... }
Note that we haven't tried to access the bytes at Packet+6
as a 32-bit quantity... they're likely to be misaligned for that. We're just asking whether the same sequence of 4 bytes exists there as exist in Op1
.
Upvotes: 2