Marius Avraam
Marius Avraam

Reputation: 11

I have troble converting some C code to Delphi

I need to convert some C code to Delphi and I got stuck at this, please help. Can I replace:

u_char chm_ac_codelens[] = {
            0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77,
    };

with

const  chm_ac_codelens =[0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, $77];

Here is a piece of code I need help with:

u_char chm_ac_codelens[] = {
        0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77,
};

u_char *
MakeQuantHeader(u_char *p, u_char *qt, int tableNo)
{
        *p++ = 0xff;
        *p++ = 0xdb;            /* DQT */
        *p++ = 0;               /* length msb */
        *p++ = 67;              /* length lsb */
        *p++ = tableNo;
        memcpy(p, qt, 64);
        return (p + 64);
}

Thanks!

Upvotes: 0

Views: 131

Answers (3)

Remy Lebeau
Remy Lebeau

Reputation: 595349

A literal translation would look like this:

var
  chm_ac_codelens: array[0..15] of Byte = ( 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, $77 );

function MakeQuantHeader(p: PByte; qt: PByte; tableNo: Integer): PByte;
begin
  p^ := $ff; Inc(p);
  p^ := $db; Inc(p); { DQT }
  p^ := 0; Inc(p);   { length msb }
  p^ := 67; Inc(p);  { length lsb }
  p^ := tableNo; Inc(p);
  Move(qt^, p^, 64);
  Inc(p, 64);
  Result := p;
end;

Upvotes: 4

Loren Pechtel
Loren Pechtel

Reputation: 9083

You're having trouble with MakeQuantHeader because it's the sort of abomination that C encourages.

It is using pointer arithmetic (one of the bug-attracting "features" of C) and mixing up characters with bytes.

Your first fix is to replace that u_char * with an array of bytes.

Your second fix is to deal with the index into the array instead of changing the "address" of the object to include the current offset.

Third is to verify that there really is enough space instead of risking stomping on memory.

Upvotes: 0

zmechanic
zmechanic

Reputation: 1990

No, I think you can't. You've defined a set not an array. The below should work for you:

program ideone;
    Const
        chm_ac_codelens : array[1..16] of Longint = (0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 119);
begin
    Writeln(SizeOf(chm_ac_codelens))
end.

I've not been working with Delphi for 17 years, but this is as close as I can get to expected behaviour. Size of array in bytes is 64, as expected by your C code.

You can see my attempt here: http://ideone.com/p0KQrl

Upvotes: 0

Related Questions