Re: Newbie question on string operators in C#



Richard <rp@xxxxxx> wrote:
Can anyone help a VB programmer understand the following C# code snippet
please? This is excerpted from a base conversion function that converts s (a
string representing a number in any base 2 to 36) into a string representing
the number in another base.

if (s[i] >= 'A' && s[i] <= 'Z') { fs[k++] = 10 + (int)(s[i] - 'A'); }

si[i] is simply a character in a string passed to the function.

fs, according to the author, is an "array of integer digits representing the
number in base:from".

What I don't understand is .... (int) (s[i] - 'A') , since both s[i] and A
are characters.

If, say, s[i] evaluates to 'F', then how does C# treat (int) ('F' - 'A')?
Does it simply convert the two characters into their ASCII numbers, thereby
evaluating it to 5?

Pretty much - except using Unicode, not just ASCII. In fact, the (int)
part is unnecessary, as there's no operator to subtract one char from
another - both are promoted to int first, then the subtraction occurs
with an int result.

--
Jon Skeet - <skeet@xxxxxxxxx>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
.



Relevant Pages

  • Newbie question on string operators in C#
    ... Can anyone help a VB programmer understand the following C# code snippet ... This is excerpted from a base conversion function that converts s (a ... string representing a number in any base 2 to 36) into a string representing ... Does it simply convert the two characters into their ASCII numbers, ...
    (microsoft.public.dotnet.languages.csharp)
  • RE: Newbie question on string operators in C#
    ... C++ to Java ... characters have this dual nature - what your intuition says characters are in ... This is excerpted from a base conversion function that converts s (a ... string representing a number in any base 2 to 36) into a string representing ...
    (microsoft.public.dotnet.languages.csharp)
  • RE: Newbie question on string operators in C#
    ... characters have this dual nature - what your intuition says characters are in ... C++ to Java ... This is excerpted from a base conversion function that converts s (a ... string representing a number in any base 2 to 36) into a string representing ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: equivalent of chomp in perl
    ... removing the "\n" at the end of a stdin? ... int flushln{ ... If you happen to know what Perl's chomp function does (which is ...
    (comp.lang.c)
  • Re: equivalent of chomp in perl
    ... removing the "\n" at the end of a stdin? ... int flushln{ ... If you happen to know what Perl's chomp function does (which is ...
    (comp.lang.c)