0

How can I convert this vfp code to c#

Function PlainToHex(inputString)
   Local myString
   myString = ""
   Do While Len(inputString) > 0
     myString = myString + Right(Transform(Asc(inputString), "@0"), 2)
     inputString = SubStr(inputString, 2)
   EndDo
 Return myString
EndFunc

I have tried looking up msdn but there are not enough examples for these vfp functions.

mehwish
  • 199
  • 3
  • 15
  • 1
    Possible duplicate of [Convert string to hex-string in C#](http://stackoverflow.com/questions/16999604/convert-string-to-hex-string-in-c-sharp) – Sinatr Apr 04 '17 at 15:22
  • Asc : https://msdn.microsoft.com/en-us/library/aa977280(v=vs.71).aspx Transform : https://msdn.microsoft.com/en-us/library/aa978614(v=vs.71).aspx Right : https://msdn.microsoft.com/en-us/library/aa978263(v=vs.71).aspx SubStr : https://msdn.microsoft.com/en-us/library/aa978501(v=vs.71).aspx Len : https://msdn.microsoft.com/en-us/library/aa977928(v=vs.71).aspx – PaulF Apr 04 '17 at 15:26
  • is Asc() single character or a string of characters ? – mehwish Apr 04 '17 at 15:59
  • If you read the link you will find it can be either - if it is a string only the first character is converted. So the code is taking the first character of the string and converting to the ASCII value, converting it to hex & appending the rightmost 2 characters to the final string (this should not be necessary as the value should be 2 characters). The substring just takes the entire string from the second character (in VFP strings are 1-based not 0 as in C#) – PaulF Apr 04 '17 at 16:40
  • 1
    @PaulF, right 2 is needed because the result of transform(, "@0") is 10 characters, i.e.: 0x7FFFFFFF. – Cetin Basoz Apr 04 '17 at 18:48
  • As a VFP function it is not needed to make it this long. You could directly use strconv() function. – Cetin Basoz Apr 04 '17 at 18:50
  • @CetinBasoz - thank you for clarifying that, I had forgotten the result was 8 hex chars + 0x prefix - I did think the vfp function could be simpler but assumed OP was converting something existing – PaulF Apr 04 '17 at 22:43
  • @PaulF, OP chose one of the longest and slowest ways to do that :) I can think of at least 4 simpler ways and It really is - strconv(inputString, 15) - only. – Cetin Basoz Apr 05 '17 at 07:26

2 Answers2

1

You could try something like this:

void Main()
{
    string test = "This is a string";
    string result = PlainToHex(test);

    Console.WriteLine(result);
}

public string PlainToHex(string inputString)
{
    return string.Join("", inputString.Select(c => ((int)c).ToString("X2")).ToArray());
}
Chris Dunaway
  • 10,974
  • 4
  • 36
  • 48
  • This is nice, you don't need ToArray(). i.e.: return string.Join("",inputString.Select(b => ((byte)b).ToString("X2"))); – Cetin Basoz Apr 04 '17 at 18:45
1

This also should work:

public string PlainToHex(string input)
{
    return BitConverter.ToString(Encoding.Default.GetBytes(input)).Replace("-", "");
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43