This is a "string2Hz" algorythm ; It is used to return the Hz of a
string is entered. This is the syntax:
[key][octave](optional [in/decrement (+/-)])
So for example:
C1
a1
a1+
c1+
These for example have to return error:
a+1
q1
cc1+
(error is 0 at this code)
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define A1BASE 440
char tmpchar[255];
int octave_man(void) // gets complete Hz-number of string tmpchar ... .
{
char *tmpchar2,*tmpchar3,*tmpchar4,*tmpchar5;
char *alphabad[] = { "a","b","c","d","e","f","g" };
int inti,inti2;
strncpy(tmpchar2,tmpchar,2); // kick possible garbage out, this mks it "user-friendly"
if((strcmp("a1",tmpchar)) == 0) //we use tmpchar to make it bug-free ... .
return A1BASE; // we don't need a huge calculation to define A1-value !!!
for(inti=0;inti<=7;inti++) // count up the scale
{
if((strncmp(tmpchar2,alphabad[inti],0)) == 0)
{
strncpy(tmpchar3,tmpchar2,0); // seperation
for(inti2 = 0;inti2<=6;inti2++) // count up the octave
{
sprintf(tmpchar4,"%s%d",tmpchar3,inti2); // tmp-usement
if((strncmp(tmpchar2,tmpchar4,2)) ==0 )
{
sprintf(tmpchar4,"%d",inti2); // real association!
break;
}
}
sprintf(tmpchar5,"%s%d",tmpchar3,tmpchar4);
if((strcmp(tmpchar5,tmpchar2)) == 0)
return ((A1BASE + (A1BASE/7*inti))*inti2); // return tone+octave as absolute Hz
strcat(tmpchar5,"+");
if((strcmp(tmpchar5,tmpchar2)) == 0)
return ((A1BASE + (A1BASE/7*inti))+(A1BASE/14)*inti2);//return tone+octave+ as absolute Hz
sprintf(tmpchar5,"%s%d-",tmpchar3,tmpchar4);
if((strcmp(tmpchar5,tmpchar2)) == 0)
return ((A1BASE + (A1BASE/7+inti))-(A1BASE/14)*inti2);//return tone+octave- as absolute Hz
}
// if we leave the for(); loop generally, somebody entered something very
// stupid! IT IS NOT VERY INTELIGENT TO POINT THIS OUT AFTER CALC SO MUCH :)
}
//recapitulation: alphabad : the scale
// tmpchar2 : whole string
// tmpchar3 : tone
// tmpchar4 : octave
// tmpchar5 : is just a tmp-char :)
// init : integer used for the scale
// inti2 : integer used for the octave
return 0;
}
int main(int argc, char *argv[])
{
int integer;
scanf("%s",tmpchar);
if((integer =octave_man()) == 0)
{
printf("error!\n");
return 1;
}
else
{
printf("%d\n",integer);
return 0;
}
}
A short appendix: The math behind it:
a1 = 440 Hz, a2 = 880! So b1 is (a1+(a1/7*key))*octave ,
so (A1 + (A1/7*1)) *1 = 502.857 (503 = B1 )!
A general formula to calculate a full key is:
(A1 + (A1/7*x)) *y
(X = Number of the key: a is 1 , b is 2, c is 3 ,... | Y = Octave )
This means:
a1 b1 c2 d2 e2 f2 g2 a2
440 503 566 629 691 754 817 880
If I have to calculate with incrementation, I just do:
(A1 + (A1/7*x) + (A1/14) *y
---------
Please, could somebody reply and tell me where make
octave_man() errors?