Converting C# code to Java code - c#

I have to convert this little piece of C# code to Java:
const int AM = 65521;
int GetCCSufix(string a)
{
int c = 1, b = 0, d, e;
var chars = a.ToCharArray();
for(e =0; e< chars.Length; e ++)
{
d = chars[e];
c = (c + d) % AM;
b = (b + c) % AM;
}
return b << 16 | c;
}
And I made it this:
private int getSuffix(String a) {
int constant = 65521;
int c = 1;
int b = 0;
int d = 0;
int e = 0;
for(e = 0; e < a.length(); e++){
d = a.charAt(e);
c = (c + d) % constant;
b = (b + c) % constant;
}
return b << 16 | c;
}
However, this doesn't seem to give me the same output as the C# code. What am i doing wrong?

I did a verbatim translation of the original code, see if this gives the correct result. What values are you using for testing, that give different results?
private static final int AM = 65521;
int getCCSuffix(String a) {
int c = 1, b = 0, d = 0, e;
char[] chars = a.toCharArray();
for (e = 0; e < chars.length; e++) {
d = chars[e];
c = (c + d) % AM;
b = (b + c) % AM;
}
return b << 16 | c;
}

Related

ParameterizedThreadStart error, no overload for 'subroutine' matches delegate ParameterizedThreadStart

I am trying to create a thread which creates generates new RSA keys using my algorithm provided.
The algorithm may not be perfect but is fine by what i am doing - not the problem.
The problem lies with why doesnt the parts below work: from what i have gathered online i am using parameterizedthreadstart correctly?
Thread thread = new Thread(new ParameterizedThreadStart(GenerateKeys)); //issue here!!!!
thread.Start(RSA_KEYS, PublicKeysToDistribute);
it shows the error: no overload for 'GenerateKeys' matches delegate ParameterizedThreadStart.
Any help would be appreciated
static void Main(string[] args)
{
Dictionary<(BigInteger, BigInteger), (BigInteger, BigInteger)> RSA_KEYS = new Dictionary<(BigInteger, BigInteger), (BigInteger, BigInteger)>();
Queue<(BigInteger, BigInteger)> PublicKeysToDistribute = new Queue<(BigInteger, BigInteger)>();
Thread thread = new Thread(new ParameterizedThreadStart(GenerateKeys));
thread.Start(RSA_KEYS, PublicKeysToDistribute);
//recipitent receives public key in form e,n
//splits into Biginteger array : {e,n}
GenerateKeys(RSA_KEYS, PublicKeysToDistribute);
BigInteger[] PublicKey = Array.ConvertAll(PublicKeyRequest(PublicKeysToDistribute).Split(':'), BigInteger.Parse);
string input;
//creates message to encrypt
input = InputToAscii();
//encrypt using PublicKey
BigInteger a = encrypt(PublicKey, input);
BigInteger b = decrypt((RSA_KEYS[(PublicKey[0], PublicKey[1])]).Item1, (RSA_KEYS[(PublicKey[0], PublicKey[1])]).Item2, a);
Console.WriteLine(AsciiToOutput(b));
Console.ReadLine();
}
private static string PublicKeyRequest(Queue<(BigInteger, BigInteger)> PublicKeysToDistribute)
{
string publickey = PublicKeysToDistribute.Peek().Item1 + ":" +PublicKeysToDistribute.Peek().Item2;
PublicKeysToDistribute.Dequeue();
return publickey;
}
//create a key value pair where the publickey is key and private key is value
//publickey = {biginteger,biginteger} where {e,n}
//privatekey = {biginteger,biginteger} where {d,n}
public static void GenerateKeys(Dictionary<(BigInteger, BigInteger), (BigInteger, BigInteger)> RSA_KEYS, Queue<(BigInteger, BigInteger)> PublicKeysToDistribute)
{
int p = 4201; //default use 61 4201
int q = 4007; //default use 53 4007
int n = p * q;
// compute the totient, phi
int ϕn = (p - 1) * (q - 1);
//e for random number which 1 < e < ϕn and is co prime of ϕn
Random rn = new Random();
bool found = false;
BigInteger e = 0;
while (found == false)
{
e = rn.Next(1, ϕn);
if (Coprime(ϕn, e) == true)
{
break;
}
}
// where (d * e) mod ϕn = 1 find d
BigInteger d = 0;
for (int k = 1; k < ϕn; k++)
{
if ((k * e) % ϕn == 1)
{
d = k;
break;
}
}
Console.WriteLine("p="+p+",q="+q+",n="+n+",phi="+ϕn+",e="+e+",d="+d+",n="+n);
Console.WriteLine("Public key: e = " + e + " n = " + n);
Console.WriteLine("Private key: d = " + d + " n = " + n);
RSA_KEYS.Add((e, n), (d, n));
PublicKeysToDistribute.Enqueue((e, n));
Console.WriteLine("added new key to dictionary");
//return new KeyValuePair<(BigInteger, BigInteger), (BigInteger, BigInteger)>((e,n),(d,n));
}
private static BigInteger encrypt(BigInteger[] PublicKey, string input)
{
BigInteger m = BigInteger.Parse(input); //m = message
BigInteger c = eMod(m, PublicKey[0], PublicKey[1]); //cipher text = (message ^ e) mod n
return c;
}
private static BigInteger decrypt(BigInteger d, BigInteger n, BigInteger c)
{
BigInteger f = eMod(c, d, n); //result test = cipher ^ d mod n
return f;
}
private static BigInteger eMod(BigInteger a, BigInteger b, BigInteger c) //where a^b % c;
{
//base case
if (b == 0)
{
return 1;
}
else if (b % 2 == 0)
{
BigInteger d = eMod(a, b / 2, c);
//int result = d * d % c;
return ((d * d) % c);
}
else
{
return ((a % c) * eMod(a, b - 1, c)) % c;
}
}
private static BigInteger GetGCDByModulus(BigInteger value1, BigInteger value2)
{
while (value1 != 0 && value2 != 0)
{
if (value1 > value2)
value1 %= value2;
else
value2 %= value1;
}
return BigInteger.Max(value1, value2);
}
private static bool Coprime(BigInteger value1, BigInteger value2)
{
return GetGCDByModulus(value1, value2) == 1;
}
private static string InputToAscii()
{
Console.Write("Enter values to encrypt:");
char[] input = Console.ReadLine().ToCharArray(); //-1 < input < 999;
//char[] input = "-1".ToCharArray();
string AsciiInput = string.Empty;
for (int i = 0; i < input.Length; i++)
{
AsciiInput += ((int)input[i]).ToString();
}
Console.WriteLine(AsciiInput);
return AsciiInput;
}
private static string AsciiToOutput(BigInteger input)
{
string inputstring = input.ToString();
string output = string.Empty;
for (int i = 0; i < inputstring.Length / 2; i++)
{
output += (char)Convert.ToInt32((inputstring.Substring(i * 2, 2)));
}
return output;
}
}

C# - Vsprintf equivilant?Converting Char to Int

Using vsprintf, the c code below converts a char array to an int. How would I do this in c#? I have tried casting the c# string to an int, and then adding the values, but the return result is not the same. My c# code needs to return the same value as the c code does(3224115)
C# Code
var astring = "123";
int output = 0;
foreach(char c in astring){
var currentChar = (int)c;
output += c;
}
//output = 150
C Code
void vout(char *string, char *fmt, ...);
char fmt1 [] = "%d";
int main(void)
{
char string[32];
vout(string, fmt1, '123'); //output is 3224115
printf("The string is: %s\n", string);
}
void vout(char *string, char *fmt, ...)
{
va_list arg_ptr;
va_start(arg_ptr, fmt);
vsprintf(string, fmt, arg_ptr);
va_end(arg_ptr);
}
Finally figured out. Could be a bit cleaner, but it works, and gets the same output as the c code.
public static ulong getAsciiLiteral(string x)
{
int len = x.Length;
string[] strArray = new string[32];
byte[] finalByte = new byte[32];
int i = 0;
int i2 = 0;
int i3 = 0;
int offset = 0;
var hexFinalString = "0x";
var bytes = Encoding.ASCII.GetBytes(x);
if(len >= 5)
{
while (true)
{
if (4 + i3 == len)
{
offset = i3;
break;
}
else
{
i3++;
}
}
}
foreach (byte b in bytes)
{
strArray[i] = b.ToString("X2");
i++;
}
i = 0;
i3 = 0;
while (i3 < len - 1)
{
hexFinalString += strArray[offset];
offset++;
i3++;
}
var ret = Convert.ToUInt64(hexFinalString, 16);
return ret;
}

Find the nth element in a tribonacci series

I found this as a Microsoft interview question (see Round 4). I am trying to solve it using C#. My attempt:
private static int NTerm_Tribonacci(int term)
{
int a = 0;
int b = 1;
int c = 1;
int result = 0;
if (term == 1) return a;
if (term == 2) return b;
if (term == 3) return c;
for (int i = 4; i <= term; i++)
{
a = a + b + c; if ((1 + 3 * i) % term == 0) { result = a; break; }
b = a + b + c; if ((2 * i + i - 1) % term == 0) { result = b; break; }
c = a + b + c; if ((3 * i) % term == 0) { result = c; break; }
}
return result;
}
But it is somehow not working var res = NTerm_Tribonacci(5);//should be 4 but getting 44
How can I solve this?
Tribonacci Number
Try this:
private static int NTerm_Tribonacci(int term)
{
int a = 0;
int b = 1;
int c = 1;
int result = 0;
if (term == 0) result = a;
if (term == 1) result = b;
if (term == 2) result = c;
while(term > 2)
{
result = a + b + c;
a = b;
b = c;
c = result;
term--;
}
return result;
}
Note that as per the definition in your link, I have assumed the first term to be T0, not T1.
Demo
I like the "LINQ way" of solving such things:
public IEnumerable<long> InfiniteTribonacciSequence()
{
long a = 0, b = 1, c = 1;
long nextTerm;
yield return a;
yield return b;
yield return c;
while (true)
{
nextTerm = a + b + c;
yield return nextTerm;
a = b;
b = c;
c = nextTerm;
}
}
But this has to be used carefully, because Methods like Min() will go crazy with this. But you can use e.g. InfiniteTribonacciSequence.Take(5).Last() to get the 5th element of the sequence.
I think the recursive way is too suitable for such cases:
example:
using System.IO;
using System;
class Program
{
static void Main()
{
int a=4, b;
b=tribo(a);
Console.WriteLine(b);
}
static public int tribo(int n)
{
if(n==0) return 0;
if(n==1) return 1;
if(n==2) return 1;
return(tribo(n-1)+tribo(n-2)+tribo(n-3));
}
}
this gives the series 0 1 1 2 4 7 13 24 ...

How to Convert Javascript Code to C# Code

I have a Javascript method. I wrote on C# but it dosen't work.
Javascript Code
var __AM = 65521;
function cc(a) {
var c = 1, b = 0, d, e;
for (e = 0; e < a.length; e++) {
d = a.charCodeAt(e);
c = (c + d) % __AM;
b = (b + c) % __AM;
}
return b << 16 | c;
}
My written C# Code
private string CC(string a)
{
var __AM = 65521;
int e;
long d;
long c = 1, b = 0;
for (e = 0; e < a.Length; e++)
{
var p = Encoding.Unicode.GetBytes(a[e].ToString());
d = Convert.ToInt32(p.First());
c = (c + d) % __AM;
b = (b + c) % __AM;
}
return b.ToString() + c.ToString();
}
JS Test
cc("4JipHEz53sU1406413803");
Result: 1132332429
C# Test
CC("4JipHEz53sU1406413803");
Result: 172781421
How Can I get JS value in C#?
This code works:
private string cc(string a)
{
var __AM = 65521;
int e;
long d;
long c = 1, b = 0;
for (e = 0; e < a.Length; e++)
{
d = (int)a[e];
c = (c + d) % __AM;
b = (b + c) % __AM;
}
return (b << 16 | c).ToString();
}

Rabin-Karp string matching algorithm by rolling hash

Here is an implementation of Rabin-Karp String matching algorithm in C#...
static void Main(string[] args)
{
string A = "String that contains a pattern.";
string B = "pattern";
ulong siga = 0;
ulong sigb = 0;
ulong Q = 100007;
ulong D = 256;
for (int i = 0; i < B.Length; i++)
{
siga = (siga * D + (ulong)A[i]) % Q;
sigb = (sigb * D + (ulong)B[i]) % Q;
}
if (siga == sigb)
{
Console.WriteLine(string.Format(">>{0}<<{1}", A.Substring(0, B.Length), A.Substring(B.Length)));
return;
}
ulong pow = 1;
for (int k = 1; k <= B.Length - 1; k++)
pow = (pow * D) % Q;
for (int j = 1; j <= A.Length - B.Length; j++)
{
siga = (siga + Q - pow * (ulong)A[j - 1] %Q) % Q;
siga = (siga * D + (ulong)A[j + B.Length - 1]) % Q;
if (siga == sigb)
{
if (A.Substring(j, B.Length) == B)
{
Console.WriteLine(string.Format("{0}>>{1}<<{2}", A.Substring(0, j),
A.Substring(j, B.Length),
A.Substring(j +B.Length)));
return;
}
}
}
Console.WriteLine("Not copied!");
}
but it has one problem if i change the position of second string than it shows result not copied but
string A = "String that contains a pattern.";
string B = "pattern";
here it shows not copied
string A = "String that contains a pattern.";
string B = "Matches contains a pattern ";
i want to check whether it is copy from first string or not even i would add something in it it or change the position but it shouldn't make difference so how to change it that it would just compare the hashes of each word in string than implement it............
Change
string B = "Matches contains a pattern ";
to
string B = "contains a pattern ";
and it will work

Categories