Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

translate C unsigned long long and bitwise in for loop to c#

Tags:

c

c#

Having

int i, k;
unsigned long long x, y;
k = 5;
for (x = 0; x < 1ULL<<(2*k); ++x) {
    for (i = 0, y = x; i < k; ++i, y >>= 2)
        putchar("ACGT"[y&3]);
    putchar('\n');
}

How can I translate for (x = 0; x < 1ULL<<(2*k); ++x) unsigned long long 1ULL and bitwise to c#?

I was trying

    public static ulong aux(int val){
        ulong result = ????? << val;
        return result;
    }
    public static void main() {
        int i;
        int k =5;  
        ulong  x,y;
        for (x = 0; x < aux(2*k) ; ++x) {
            for (i = 0, y = x; i < k; ++i, y >>= 2){
                Console.Write("ACGT"[y&3]);
            }
            Console.WriteLine();
    }

How to translate that parts of code x < 1ULL<<(2*k); and "ACGT"[y&3]?

like image 952
edgarmtze Avatar asked Dec 01 '13 18:12

edgarmtze


3 Answers

Both lines can be expressed very similarly in C#. The C line:

 for (x = 0; x < 1ULL<<(2*k); ++x) {

Translates in C# to

 for (x = 0; x < 1UL<<(2*k); ++x) {

(Note the suffix 1UL (unsigned long) instead of 1ULL (unsigned long long).

The C line

putchar("ACGT"[y&3]);

Requires a cast in C# and translates to

Console.Write("ACGT"[(int)y & 3]);

The cast is required because the indexer, String.Chars, can only accept a signed integer as an argument.

like image 112
drf Avatar answered Nov 14 '22 06:11

drf


The trick is to work out what the C code is actually doing, rather than trying to translate directly. The term 1ULL<<(2*k) just means "take value 1 and shift it ten bits to the left". In other words 2^0 becomes 2^10, which is 1024. So replace x < 1ULL<<(2*k) with x < 1024.

Likewise "ACGT"[y&3] just means "obtain the character at position y bitwise-anded with 3 from the string "ACGT". So assign "ACGT" to a named constant and use the same technique to obtain the character at that index.

like image 2
David Arno Avatar answered Nov 14 '22 05:11

David Arno


C# does not have long long and it would be hard to replace. As long as k = 5 however it is not too relevant, a simple ulong should do:

ulong result = 1UL << val;

Your troubles will start when (2*k) >= 64

And the output needs a cast to int :

 Console.Write("ACGT"[(int)(y & 3)]);
like image 1
Henk Holterman Avatar answered Nov 14 '22 07:11

Henk Holterman