How pass word number to widestring?

810 Views Asked by At

First of all I am sorry that I cannot better to describe my problem.

What I have is Word number 65025 which is 0xFE01 or 11111110 00000001 in binary. And I want to pass the value to wstr Word => 11111110 00000001.

I found that using typecast does not work.

And one more question here. If I want to add another number like 10000 => 0x03E8 how to do it. So in the result the widestring should refer to values 0xFE01 0x03E8.

And then, how to retrieve the same numbers from widestring to word back?

var wstr: Widestring;
wo: Word;
begin
  wo := 65025;
  wstr := Widestring(wo);
  wo := 10000;
  wstr := wstr + Widestring(wo);
end

Edit:

I'm giving another, simpler example of what I want... If I have word value 49, which is equal to ASCII value 1, then I want the wstr be '1' which is b00110001 in binary terms. I want to copy the bits from word number to the string.

2

There are 2 best solutions below

0
David Heffernan On BEST ANSWER

It looks like you want to interpret a word as a UTF-16 code unit. In Unicode Delphi you would use the Chr() function. But I suspect you use an ANSI Delphi. In which case cast to WideChar with WideChar(wo).

3
Rudy Velthuis On

You are casting a Word to a WideString. In Delphi, casting usually doesn't convert, so you are simply re-interpreting the value 65025 as a pointer (a WideString is a pointer). But 65025 is not a valid pointer value.

You will have to explicitly convert the Word to a WideString, e.g. with a function like this (untested, but should work):

function WordToBinary(W: Word): WideString;
var
  I: Integer;
begin
  Result := '0000000000000000';
  for I := 0 to 15 do // process bits 0..15
  begin
    if Odd(W) then
      Result[16 - I] := '1';
    W := W shr 1;
  end;
end;

Now you can do something like:

wo := 65025; 
wstr := WordToBinary(wo);
wo := 10000;
wstr := wstr + ' ' + WordToBinary(wo);

For the reverse, you will have to write a function that converts from a WideString to a Word. I'll leave that exercise to you.

Again, you can't cast. You will have to explicitly convert. Both ways.