2

So, yesterday I opened up a question about converting integer to binary, which was a little unclear to me, about how it works (with the shifting operations). Now, I have another question here to disguss: How it's done on android, why it results differently than doing it on windows, and how to get the actual binary result rather than what I get now (and about this one I'm not yet clear what it is; it's somehow hex with a wrong value).

I have this code in a firemonkey mobile project, which has both, android and windows platforms set as targets. This way the code testing can be done by targeting windows, so that it compiles faster, and previews as virtual mobile form; Well, at least the intention is to do this, but looks like it's not so reliable source of errors...

While the same project ran on Win32 worked just fine, running it on android results in not getting binary result out of a function.

I use this code to make conversions:

function IntToBin(Value: Integer): string;
var
  i: Integer;
begin
  SetLength(Result, 9);
  for i := 1 to 9 do begin
    if (Value shr (9-i)) and 1 = 0 then begin
      Result[i] := '0'
    end else begin
      Result[i] := '1';
    end;
  end;
end;

The debugger shows this, when trying to convert value '1':

Result: 0x6d09d738
   *Result: #0'00000000'                      [expanded from Result]
Value: 1

Now, I know that the reason I'm then (after the main procedure, which calls this conversion function is completed) getting exactly the half value of what it should be (1 instead of 3, 2 instead of 4, 8 isntead of 16, 6 instead of 12...) is because in *Result there is clear that it's only 8 bit, when I need 9 bit result (I'm doing conversions from Integer (1..512) to binary...), and therefore insead of reading 2 as 0010, I get 001, which is 1, instead of 6 (0110) I get 3 (011), 8 (1000) I get 4 (100) etc....

Now I really want to know why, at first, it even throws result as 0x6d09d738 / 0x6d09d738 instead of just binary, and why is it not 9bit, as I set the length of a result string?

Also, here's another interesting and for me ununderstandable thing:

This is my procedure which triggers coversion:

procedure TForm1.CalculateAddress1;
var SetDip: string;
    C: integer;
begin
  SetDip := IntToBin(StrToInt(MergeAddr));
  //Text1.Text:=SetDip;
  for C := 1 to 9 do
    begin
      if Copy(SetDip, b, 1) = '1' then
      DipSW[10-b].IsChecked:=True
      else DipSW[10-b].IsChecked:=False;
    end;
end;

// (I use this to convert dmx address into dip switch configuration...)

The SetDip gets something of a value like #0'00000000'. (it differs; this is the case when integer that was converted is 1; for 11 I get #0'00000101' );

This results as having the exact half value as it should be (as I mentioned above; And I understand why this is happening, since one bit of a result is missing...).

However, if I remove the // from Text1.Text:=SetDip;, which I putted there so I could see the result on the phone screen, I get the next error, on phone only! (again, targeting windows runs ok):

'String index out of range (-1). Must be >= 0 and <= 8';

After that, Segmentation fault is raised, 2 Access violation errors and finally, the app closes itself.

It looks like it can't copy SetDip to Text1.Text field; That's what I thought. But later I found out that this error doesn't occur always, which was weird, since it should, and not just that: it should even when I leave Text1.Text:=SetDip out of code; -> I don't know how it copyes string at index 9, if it's not that long; I know this is exactly the reason it throws the error, but again: why not always?

[[ Ps: +, found out that Firemonkey handles fixed arrays automatically, if the code tries to create entry beyond the defined size. Interesting... :) Maybe this means that it handles the string length and copy indexes by itself too..? ]]

12
  • I agree that Delphi documentation is of poor quality, but even bad documentation is intended to be read sometimes. Strings are already covered in the most relevant topic - comparing Win32 and Android coding patterns: docwiki.embarcadero.com/RADStudio/XE5/en/… Jan 28, 2014 at 6:30
  • I haven't even searshed for this, since I didn't thought about the result string and index to be the source of troubles... Too narrow observing left me focused at the length and byte itself. Also, as said, it haven't thrown the index error always, as would be expected, if I went beyond index every single time!!
    – That Marc
    Jan 28, 2014 at 6:45
  • I agree that what they did with string indices is just a little less than intentional sabotage. Still when you take a NEW development tool for a NEW platform, i expect you would read at least "quick staring guide" and "whatsnew". BTW, do you know that EXCEPT is not garanteed to catch exceptions in Delphi Mobile ? Well, maybe they changed that "feature is not a bug" in XE5, but i did not heard that. Jan 28, 2014 at 7:04
  • If you mean for MadExcept, I don't even have it there in XE5... And as for the docs, I read just a few basics, and then rather went for doing stuff. I prefer SO over Emba's docs, cuz they're quite unclear... ˘˘
    – That Marc
    Jan 28, 2014 at 7:15
  • 2
    Please don't ask at SO before reading the docs. Emba's docs on strings and mobile migration are good. You simply have to read them. Trying to pick things up in bits and pieces will lead to you learning bad habits. Jan 28, 2014 at 7:42

3 Answers 3

1

On Android (and other mobile platforms), the first character in a string is indexed with the value 0, whereas on desktop versions, it is indexed with the value 1.

So, you need to change

Result[i] := '0'

with

Result[i-1] := '0'

when compiling for mobile platforms. In order to do this automatically, you can use the following:

{$IFDEF CPUARM }
  Result[i-1] := '0'
{$ELSE }
  Result[i] := '0'
{$ENDIF }

But beware that it is only INDEXING (ie. using the [] syntax) that is different. The Copy, Pos, etc. functions still treat 1 as the first character in a string.

Talk about inconsistency (and a programmer's headache)...

I use the following helper functions:

FUNCTION GetChar(CONST S : STRING ; OneBasedIndex : Cardinal) : CHAR;
  BEGIN
    IF LOW(STRING)=0 THEN Result:=S[PRED(OneBasedIndex)] ELSE Result:=S[OneBasedIndex]
  END;

PROCEDURE SetChar(VAR S : STRING ; OneBasedIndex : Cardinal ; C : CHAR);
  BEGIN
    IF LOW(STRING)=0 THEN S[PRED(OneBasedIndex)]:=C ELSE S[OneBasedIndex]:=C
  END;

to get/set a character, regardless of compilation target. It also has the advantage of being "future proof", since it doesn't use the compiler's {$DEFINE}s, but checks the low index of the STRING type.

15
  • Ohh... that's the thing -.- So I'll have to go with ifdef os definition, to have it for both platforms available, right?
    – That Marc
    Jan 28, 2014 at 5:46
  • Right now, I solved this with SetLength(Result, 9); for i := 1 to 9 do begin if (Value shr (8-i)) and 1 = 0 then begin Result[i] := '0' end else begin Result[i] := '1'; and followed with final statement, before ending the procedure that called this function, if Value > 255 then DipSw[9].IsChecked:=True else DipSw[9].IsChecked:=False where Value is the integer sent to function; This way I actually do the same as on Windows 8 bit, and deal with the last bit manually. Its not perfect, but at least works. Didn't know about the index thing. Will check asap after work. Thx
    – That Marc
    Jan 28, 2014 at 5:53
  • Wow! Wait, but the copy uses offset as by number of chars, or as index of a string? If I understand correctly, I have to treat the string everywhere the same, except for locating chars inside of it by index, where I need to pull -1? :O That's ridiculous...
    – That Marc
    Jan 28, 2014 at 5:55
  • 1
    And you're right. Strings are the same all over, except in []. And the string helper functions (STRING.IndexOf('...') and the like) works with 0 as first character, in both mobile and desktop versions.
    – HeartWare
    Jan 28, 2014 at 6:03
  • 1
    "So I'll have to go with ifdef os definition, to have it for both platforms available, right?" - no. You just fix a settings into your project options or put a compiler pragma to your sources, and kill this insanity and always use strings 1-based: docwiki.embarcadero.com/RADStudio/XE4/en/… Jan 28, 2014 at 6:26
1

Here is a solution that is not depending on which index the strings starts with (i.e. platform independent):

function IntToBin(Value: Integer): String; 
var 
  i: Integer; 
  pStr: PChar; 
begin 
  SetLength( Result,9); 
  pStr := PChar(Pointer(Result));  // Get a pointer to the string
  for i := 8 downto 0 do begin 
    pStr[i] := Char(Ord('0') + ((Value shr (8 - i)) and 1)); 
  end; 
end;
3
  • Can't you write pStr := PChar(Result)? Jan 28, 2014 at 9:30
  • @DavidHeffernan, yes but there is a trick involved here. By using the Pointer() cast, you avoid the extra call to @UStrToPWChar.
    – LU RD
    Jan 28, 2014 at 9:35
  • OK. That avoids the length 0 check. You may as well write pStr := Pointer(Result) I suppose. This is why I like ZBS, given that it is compulsory on mobile. Jan 28, 2014 at 9:41
1

Your problems are because on the mobile platform, string indexing is zero based, and by default on desktop platforms it is one based. There are a number of ways to deal with this, and you certainly do not need platform switching ifdefs.

The easiest solution is to use {$ZEROBASEDSTRINGS ON} to make the desktop compiler behave the same way as does the mobile compiler.

When you add this to your code then you will need to get used to zero-based indexing for your strings. You should stop using legacy functions like Pos and instead use the TStringHelper methods.

Your function would be re-written like this:

{$ZEROBASEDSTRINGS ON}
function IntToBin(Value: Integer): string;
var
  i: Integer;
begin
  SetLength(Result, 9);
  for i := 0 to 8 do begin
    if (Value shr (8-i)) and 1 = 0 then begin
      Result[i] := '0'
    end else begin
      Result[i] := '1';
    end;
  end;
end;

The code is, in my view, a little cleaner and avoids branching if written like this:

{$ZEROBASEDSTRINGS ON}
function IntToBin(Value: Integer): string;
var
  i: Integer;
begin
  SetLength(Result, 9);
  for i := 0 to 8 do
    Result[i] := Chr(ord('0') + (Value shr (8-i)) and 1));
end;

The other mooted change to strings, which has not yet happened, is to make them immutable. That change would make the string indexing operator read-only. That change might never happen. If it did then I would probably re-write the code as follows:

function IntToBin(Value: Integer): string;
var
  i: Integer;
  buff: array [0..8] of Char;
begin
  for i := 0 to 8 do
    buff[i] := Chr(ord('0') + (Value shr (8-i)) and 1));
  SetString(Result, PChar(@Buffer), Length(buff));
end;

You should certainly have a read of the documentation on this subject: http://docwiki.embarcadero.com/RADStudio/en/Migrating_Delphi_Code_to_Mobile_from_Desktop

The other thing that you simply must do, at the very least for debug builds, is to enable range checking. Had that been enabled, the compiler would have written out code that would have revealed your error immediately. It is best to control this feature globally through the project configuration.

8
  • 1
    You can also use Low(String) to get correct 0-based or 1-based starting index without using {$ZEROBASESTRINGS} to change it: Result[Low(Result)+I] := ...; Jan 28, 2014 at 8:15
  • @RemyLebeau: I already do this in my helper functions above. Doing this, the code will be target agnostic and should work in all combinations of targets and compilers.
    – HeartWare
    Jan 28, 2014 at 8:17
  • @HeartWare: you can get rid of the if statements: Result := S[Low(S)+Pred(OneBasedIndex)] and S[Low(S)+Pred(OneBasedIndex)] := C; Jan 28, 2014 at 8:23
  • @Remy Indeed there are other ways as I mentioned. I described the simplest. Try writing the code in the question with low(). It's not very clear. Jan 28, 2014 at 8:32
  • Sadly the ZBS convention will make it difficult to write clear code using Low() with complex string handling routines. I'm not a big fan of TStringHelper and TStringBuilder syntax. Too much of my codebase would have to be reviewed/rewritten to support all platforms. Biding my time till I see a clear solution.
    – LU RD
    Jan 28, 2014 at 8:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.