So, I got a "s: string" which I need to convert this to ASCII.

So, I got a "s: string" which I need to convert this to ASCII.

The issue is that s may contain non-ASCII characters, in which case I want to raise an exception.

For the life of me I can't find any TEncoding function which returns any error code or similar.

Any ideas?

Comments

  1. From what I see I'll basically have to reimplement TMBCSEncoding, as LocaleCharsFromUnicode has an optional parameter which lets me know if the input has invalid characters. Of course TMBCSEncoding completely ignores this parameter...

    ReplyDelete
  2. Simply loop over the string and raise an exception if Ord(s[i]) >= 128 or part of a surrogate pair?

    ReplyDelete
  3. Stefan Glienke If I got to roll my own, I'd rather make something a bit more flexible. The RTL is so least-effort at times it's annoying.

    ReplyDelete
  4. Simon Stuart He was asking for ASCII and not ANSI. Remember that ANSI also contains the upper half of the byte and is affected by the current codepage. That means your code will not work properly.

    ReplyDelete
  5. Asbjørn Heid Not having to use any of the encoding options (yet) but do you have to re-implement all TMBCSEncoding? Couldn't you subclass it and override so you can add the error checking where required?

    ReplyDelete
  6. Nicholas Ring It's not a huge class but as far as I could see, pretty much.

    ReplyDelete
  7. Asbjørn Heid Oops - Didn't fully read the MSDN and didn't realise that the error result was a return value :-( Sorry about that.

    ReplyDelete
  8. Hi, something like this?
    ********************************************
    function WideStringToAnsiString(
    const ws: WideString;
    codePage: Word): AnsiString;
    var
    l      : Integer;
    tmpANSI: AnsiString;
    begin
    tmpANSI := '';
    Result := '';
    if ws = '' then Exit;
    try
    try
    l := WideCharToMultiByte( //
    codePage,            //
    WC_COMPOSITECHECK or WC_DISCARDNS or WC_SEPCHARS or WC_DEFAULTCHAR, //
    @ws[1],//
    -1,     //
    nil,    //
    0,      //
    nil,    //
    nil     //
    );
    SetLength(tmpANSI, l - 1);
    if l > 1 then WideCharToMultiByte( //
    codePage,                //
    WC_COMPOSITECHECK or WC_DISCARDNS or WC_SEPCHARS or WC_DEFAULTCHAR, //
    @ws[1],     //
    -1,          //
    @tmpANSI[1],//
    l - 1,       //
    nil,         //
    nil);
    except
    On E: Exception do raise Exception.Create('Exception in "WideStringToAnsiString" metod :  ' + E.Message);
    end;
    finally
    Result := tmpANSI;
    end;
    end;
    ********************************************

    ReplyDelete

Post a Comment