4

I translated a VB6 module containing a couple of encryption functions into c#, I have the following aritmethic operation in both sides:

C#:

int inter, cfc;
inter = 6940;
cfc = Convert.ToInt32((((inter / 256) * 256) - (inter % 256)) / 256);
//cfc = 26

VB6:

Dim inter As long
Dim cfc As long     
inter = 6940
cfc = (((inter / 256) * 256) - (inter Mod 256)) / 256
'cfc = 27

I haven't been able to figure out the result mismatch since all operations are returning integer numbers, this is causing the encryption process to work unexpectedly.

1 Answers1

9

In C# (inter / 256) does integer division, while VB6 does not. So in one of your code samples the result of that division is being truncated to 27 before the rest of the operations, while the other uses a value of 27.109375. This is leading to the difference in your end results.

Use (inter \ 256) in VB6 if integer division is what you intend.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
  • The VB6 code has the behavior I'd like to replicate actually. I need the operation in C# to result exactly as VB6. – Lirio Lebrón Nov 17 '17 at 14:31
  • @LirioLebrón You can either divide by 256.0 in C# to coerce it to do non-integer division, or cast `inter` to `double` (if you were dividing two integer variables). – Bill the Lizard Nov 17 '17 at 14:36
  • 1
    If you want floating point division. then what is the point of `(inter / 256) * 256` ? – Dennis_E Nov 17 '17 at 14:36
  • @BilltheLizard adding the .0 did the trick, thank you very much. – Lirio Lebrón Nov 17 '17 at 14:43
  • 2
    @Dennis_E Not only that. If one actually decides to use floating point division there, the entire code is just a funky way to write `int cfc = inter / 256` (C#). I can't see any sane reason to do so. – Milster Nov 17 '17 at 14:57