Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an arbitrary string encoding?

I'm trying to get some code working against an API published by a Chinese company. I have a spec and some sample code (in Java), enough to understand most of what's going on, but I ran across one thing I don't know how to do.

String ecodeform = "GBK";
String sm = new String(Hex.encodeHex("Insert message here".getBytes(ecodeform)));  //test message

It's creating a string from the char array result of the hex representation of the original string, encoded in GBK format (the standard Chinese character encoding, equivalent to ASCII for English text). I can work out how to do most of that in Delphi, but I don't know how to encode a string to GBK, which is specifically required by this API.

In SysUtils, there's a TEncoding class that comes with a few built-in encodings, such as UTF8, UTF16, and "Default" (the system's default code page), but I don't know how to set up a TEncoding for an arbitrary encoding such as GBK.

Does anyone know how to set this up?

like image 783
Mason Wheeler Avatar asked Jul 22 '26 16:07

Mason Wheeler


2 Answers

You can use the TEncoding.GetEncoding() method to get a TEncoding object for a specific codepage/charset, eg:

var
  Enc: TEncoding;
  Bytes: TBytes;
begin
  Enc := TEncoding.GetEncoding(936); // or TEncoding.GetEncoding('gb2312')
  try
    Bytes := Enc.GetBytes('Insert message here');
  finally
    Enc.Free;
  end;
  // encode Bytes to hex string as needed...
end;
like image 174
Remy Lebeau Avatar answered Jul 24 '26 12:07

Remy Lebeau


TEncoding has a GetEncoding method for that. Give it the encoding name or number, and it will return a TEncoding instance.

For GBK, the number I think you want is 936. See Microsoft's list of code pages for more.

like image 32
Rob Kennedy Avatar answered Jul 24 '26 13:07

Rob Kennedy