LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C - Base 4 addition (https://www.linuxquestions.org/questions/programming-9/c-base-4-addition-719695/)

charlitos 04-16-2009 06:35 PM

C - Base 4 addition
 
Im trying to do an exercise I found on the internet(classes are over and Im bored) to generate a dna sequence using different bases.

base 1

A C G T

base 2

AA AC AG AT CA CC CG CT GA GC GG GT TA TC TG TT

base 3

AAA AAC AAG AAT ACA ACC ACG ACT ....


I thought it would be better converting letters into numbers:

A = 1
C = 2
G = 3
T = 4

and the sequence would be

base 1:
1 2 3 4

base 2:
11 12 13 14 21 22 23 24 31 32 33 34 41 42 43 44

base 3:
111 112 113 114 121 122 123 124 131 132 133 134 141 142 143 144 211...

this way I thought that if using base for addition (+ 1) I can always get the next group of numbers(letters) with basically no effort compared to the alternative of generating n loops( n = base) to get the whole sequencing.

The thing is I need a function to do base four addition, I could also start doing it myself but I was wondering if theres somethign already made I can use for this specific exercise.

Also I would appreciate any other ideas to find better ways to solve this exercise.

thanks in advance.

tuxdev 04-16-2009 07:56 PM

Start from 0, not 1. Decimal goes from 0 to 9, octal from 0 to 7, and hexadecimal from 0 to f (15). Also, 4 is a power of 2, which means it has the same niceties as octal and hexadecimal (octal is 3 bits grouped, hexadecimal is 4 bits grouped).

jlinkels 04-16-2009 09:48 PM

Like tuxdev said, it is better to use 0,1,2,3.

Then what he says about base 4 being nice, he means that you can easily convert to a base 4 number representation.

Consider (for example) a 3-digit base 4 number:

123

In hex representation that is: 0x1B, bin: 01 1011

Add one to that number, using your normal '+' function: you get 0x1C (01 1100)

Convert that back to base 4:

130

Now because number are represented binary in your computer, the easiest way to convert hex to quaternary is:

Code:

nr_digits=0;
repeat
  digit = new_number & 0x3 //leaves only the rightmost bits
  new_number = new_number shr 2 //move to the next digit
  nr_digits++
until nr_digits >= max_digits;

How to string all those digits together I leave happily to you. Above code is not syntactically correct but you get the idea.

Any chance to implement those DNA strings and create a dino?

jlinkels


All times are GMT -5. The time now is 08:25 PM.