/* * create file ob - the output binary machine code */ int create_file_ob(char *filename, CompilerNode *cn_list) { int IC,DC; int how_many_bits_to_use; char *code_length_in_binary; char *data_length_in_binary; char address_binary_string[MAX_BINARY_STR]; char linker_flag_string[MAX_LINKER_STR]; FILE *fp; char *filefullname = (char *)calloc(strlen(filename) + 1, sizeof(char)); /*allocate memory for filename */ strcpy(filefullname,filename); filefullname = strcat(filefullname, OBJECT_FILE_EXT); /* add extension to filename */ filefullname[strlen(filefullname)] = '\0'; fp = fopen(filefullname, "w"); if(!fp) return CREATE_FILE_ERR; /* error occurred while trying to create new file*/ IC = get_instruction_counter(); DC = get_data_counter(); how_many_bits_to_use = (IC <= BYTE_MAX_NUM) ? ONEBYTE_BITSNUM : TWOBYTES_BITSNUM; /*how many chars will the string need*/ code_length_in_binary = (char *)calloc(how_many_bits_to_use + 1, sizeof(char)); dec2bin(IC, code_length_in_binary, how_many_bits_to_use); /*translate decimal to binary string*/ how_many_bits_to_use = (DC <= HALFBYTE_MAX_NUM) ? (ONEBYTE_BITSNUM/2) : ONEBYTE_BITSNUM; /*how many chars will the string need*/ data_length_in_binary = (char *)calloc(how_many_bits_to_use + 1, sizeof(char)); dec2bin(DC, data_length_in_binary, how_many_bits_to_use); /*translate decimal to binary string*/ /* write 2th row - data and instructions size in binary */ fprintf(fp, "%45s%s %s\n", "", code_length_in_binary, data_length_in_binary); while(cn_list != NULL) { how_many_bits_to_use = (cn_list->address <= BYTE_MAX_NUM) ? ONEBYTE_BITSNUM : TWOBYTES_BITSNUM; /*set how many chars will the string need*/ dec2bin(cn_list->address, address_binary_string, how_many_bits_to_use); /*translate decimal address to binary string*/ get_linker_flag_str(cn_list->linker_flag, linker_flag_string); /* get */ fprintf(fp, OBJECT_ROW_FORMAT, address_binary_string, cn_list->binary_machine_code, linker_flag_string); cn_list = cn_list->next; /* point to next node*/ } /*free memory allocations*/ free(code_length_in_binary); free(data_length_in_binary); if(fclose(fp) != OK) return CLOSE_FILE_ERR; /*Error occured while trying to close the file Stream*/ else return OK; /* everthing is OK*/ }
/* Convert sequence \0XXXX */ static inline bool deoctify(char *p, int avail, int *eat) { uint8_t byte; char *rep = p; p += 2, (*eat)++, avail -= 2; /* Remove '\0' */ if (avail >= 1) { if (!isodigit(*p)) return false; byte = dec2bin(*p++); (*eat)++, avail--; } else { return false; } if (avail >= 1 && isodigit(*p)) { byte <<= 3; byte |= dec2bin(*p++); (*eat)++, avail--; } if (avail >= 1 && isodigit(*p)) { byte <<= 3; byte |= dec2bin(*p++); (*eat)++, avail--; } if (avail >= 1 && isodigit(*p)) { byte <<= 3; byte |= dec2bin(*p++); (*eat)++, avail--; } *rep = byte; return true; }
void dec2bin(int dec, char *bin, int pos) { if(dec <= 0){ if(0 == pos) return; *bin = '0'; *(bin+1) = 0; dec2bin(dec, bin + 1, pos - 1); } if(dec % 2) *bin = '1'; else *bin = '0'; *(bin + 1) = 0; dec2bin(dec / 2, bin + 1, pos - 1); }
bool Signatures::calcSignatures(vector<Node*> vNodes){ for(int k =0 ; k < vNodes.size();k++){ Node * node = vNodes[k]; string signature = dec2bin(node->getUpperNS())+dec2bin(node->getLowerNS()); string exitSignature = dec2bin(node->getUpperNES())+dec2bin(node->getLowerNES()); //Signature node->setSignature(bin2dec(signature)); //Exit signature node->setExitSignature(bin2dec(exitSignature)); } return true; }
void get_sign (list *num_list, uncode_tree *tree, int while_eof, const char *output_name) { FILE *output; output = fopen(output_name, "w"); char bin [8]; bin [0] = '\0'; uncode_tree *start = tree; while (num_list->next != NULL) { int val = num_list->val; dec2bin(val, bin); for (int i = 0; i < 8; i++) { if (bin[i] == '0') tree = tree->left; else tree = tree->right; if (tree->sign != '\0') { fprintf(output, "%c", tree->sign); tree = start; } } num_list = num_list->next; } int val = num_list->val; dec2bin(val, bin); int amt; if (while_eof == 0) amt = 0; else amt = 8 - while_eof; for (int i = amt; i < 8; i++) { if (bin[i] == '0') tree = tree->left; else tree = tree->right; if (tree->sign != '\0') { fprintf(output, "%c", tree->sign); tree = start; } } fclose (output); }
void Hamming_Code::generate_H(void) { int i, j, NextPos; char NotUsed; bvec temp; ivec indexes(n); indexes.zeros(); for (i = 1; i <= n - k; i++) { indexes(i - 1) = pow2i(n - k - i); } NextPos = n - k; for (i = 1; i <= n; i++) { NotUsed = 1; for (j = 0; j < n; j++) if (i == indexes(j)) { NotUsed = 0; } if (NotUsed) { indexes(NextPos) = i; NextPos = NextPos + 1; } } for (i = 0; i < n; i++) { temp = dec2bin(n - k, indexes(i)); //<-CHECK THIS OUT!!!! for (j = 0; j < (n - k); j++) { H(j, i) = temp(j); } } }
int main(int argc, char **argv) { int decres = 0; char binres[MAX_BIT_BIN + 1]; Lex *lex = NULL; if (argc != 2) { usage(argv[0]); } lex = lex_init(argv[1]); if (lex == NULL) { show_error("syntax analizator not initialized"); } decres = parse(lex); lex_free(lex); /* Convert result in binary format */ dec2bin((unsigned int)abs(decres), binres); /* Print the result */ if (decres < 0) { printf("\n\t%d\t\t\t-0x%x\t\t\t-0b%s\n\n", decres, decres, binres); } else { printf("\n\t%d\t\t\t0x%x\t\t\t0b%s\n\n", decres, decres, binres); } return 0; }
/* * create file external (filename.ext) for all external symbols * filename - current file name * external symbols list - external_symbols_list symbols list */ int create_file_ext(char *filename, Symbol *external_symbols_list) { int how_many_bits_to_use; char address_binary_string[MAX_BINARY_STR]; FILE *fp; char *filefullname = (char *)calloc(strlen(filename) + 1, sizeof(char)); /*allocate memory for filefullname */ strcpy(filefullname,filename); filefullname = strcat(filefullname, EXTERNAL_FILE_EXT); /*add extention to filename */ filefullname[strlen(filefullname)] = '\0'; fp = fopen(filefullname, "w"); if(!fp) return CREATE_FILE_ERR; /* error occured while trying to creat new file*/ while(external_symbols_list != NULL) { how_many_bits_to_use = (external_symbols_list->address <= BYTE_MAX_NUM) ? ONEBYTE_BITSNUM : TWOBYTES_BITSNUM; /*set how many chars will the string need*/ dec2bin(external_symbols_list->address, address_binary_string, how_many_bits_to_use); /*translate decimal address to binary string*/ fprintf(fp, EXT_ENT_ROW_FORMAT, external_symbols_list->name, address_binary_string); external_symbols_list = external_symbols_list->next; /* point to next node*/ } if(fclose(fp) != OK) return CLOSE_FILE_ERR; /*Error occured while trying to close the file Stream*/ else return OK; /* everthing is OK*/ }
void Analyser::run() { if(s.isEmpty()) throw QString("Error! Input is empty!"); // what if user inputs: // 1. letter, number or operator sequence: aadsdasdas or 123123123 or ~~~ except ~not // 2. numbers 2-9 one or more // 3. brackets: )( // \\w is a [a-zA-Z0-9_] QString exp = QString("(\\w){2,}|([^\\w()]){2,}(?1") + NOT +")|([2-9])+"; QRegExp word(exp); if(word.indexIn(s) != -1) throw QString("Syntax error: " + word.cap(0)); // optimization. Now full equal expressions calculates REALLY fast. this->detectEqualExpressions(); this->detectVariables(); // show progress bar pb->setValue(0); pb->show(); // start timer QTime timer = QTime::currentTime(); const int vlen = variables.length(); const long long imax = pow(2., vlen); // main calculation loop for(long long i = 0; i<imax; ++i) { QString expression = s; if(vlen > 0) // optimization { QString bits = dec2bin(i, vlen); for(int j=0; j<vlen; ++j) { expression.replace(variables[j], bits[j]); } } QChar answer = eval(expression); if(answer == ZERO) throw QString("Answer is 0. \nTime elapsed: " + QString::number(timer.elapsed()) + " ms"); else { int prev = 0; int pbvalue = (double)i / (imax/100); if(pbvalue > prev) // small optimization. pb->setValue(pbvalue); prev = pbvalue; } } throw QString("Answer is 1. \nTime elapsed: " + QString::number(timer.elapsed()) + " ms"); }
int main_2 (int argc, const char * argv[]) { int decimal = 12785; dec2bin(decimal); dec2oct(decimal); dec2hexa(decimal); return 0; }
int main() { int dec = 10; char bin[9] = {0}; dec2bin(dec, bin, 8); const char *goodip = "192.168.1.1"; const char *testip = "192.168.1.2"; printf("result=%s ret=%d\n", bin, validate(goodip, testip, 30)); return 0; }
bool Signatures::verifySignaturesD1(vector<Node*> vNodes){ bool resultBool=true; //errs()<<"verifySignaturesD1!\n"; for(int i =0 ; i < vNodes.size(); i++){ Node *node = vNodes[i]; set<Node*> succs = node->getSuccs(); //Verify //NES(Ni) and d1(Ni+1) == NS(Ni+1), if NT(Ni+1) == A //NES(Ni) xor d1(Ni+1) == NS(Ni+1), if NT(Ni+1) == X if(!succs.empty()){ __int64_t exitSigroot = node->getExitSignature(); for(set<Node*>::iterator it = succs.begin(); it != succs.end(); it++){ Node * succ = *it; __int64_t result = 0; string op; if(succ->getType()==typeA){ op ="AND"; result = node->getExitSignature() & succ->getd1Value(); }else{ op= "XOR"; result = node->getExitSignature() ^ succ->getd1Value(); } if( result != succ->getSignature()){ resultBool = false; errs()<< "Block Name: "<< node->getBB()->getName() << " Type: " <<node->getTypeStr(); errs()<< " Num succ: " <<node->getSuccs().size(); errs() <<"\n"; errs()<< " Succ Name: "<< succ->getBB()->getName()<< " Type:" <<succ->getTypeStr(); errs() <<"\n"; errs()<<" NES :"<<dec2bin(node->getExitSignature()) <<"\n"; errs()<<" D1 :"<<dec2bin(succ->getd1Value())<<"\n"; errs()<<" NS :"<<dec2bin(succ->getSignature())<<"\n"; errs()<<" Result:"<<dec2bin(result) <<"\n"; } } } } return resultBool; }
bool Signatures::verifySignaturesD2(vector<Node*> vNodes){ bool resultBool=true; //errs()<<"verifySignaturesD2!\n"; for(int i =0 ; i < vNodes.size(); i++){ Node *node = vNodes[i]; //Verify //NS(Ni) and d2(Ni) == NES(Ni+1) __int64_t result = node->getSignature() ^ node->getd2Value(); if(result != node->getExitSignature()){ resultBool = false; errs()<<"Block Name: "<< node->getBB()->getName() << " Type: " <<node->getTypeStr(); errs() <<"\n"; errs()<<"NS: "<<dec2bin(node->getSignature()) <<"\n"; errs()<<"D2: "<<dec2bin(node->getd2Value()) <<"\n"; errs()<<"NES: "<<dec2bin(node->getExitSignature()) <<"\n"; errs()<<"Result:"<<dec2bin(result) <<"\n"; errs()<<"Node D2 verification: "; errs()<<"Error!!\n"; } } return resultBool; }
int binary_gap(int N){ std::string bin_num = dec2bin(N); int gap = 0; int highest = 0; int mark = 0; for(int i = 0; i < bin_num.size(); i++){ if(bin_num[i] == '1'){ gap = i - mark; mark = i; if(gap > highest) highest = gap - 1; } } return highest; }
void add(char x1[], char x2[], char result[]) { char man1[23] = {(char)0}; char man2[23] = {(char)0}; char resMan[23] = {(char)0}; char resExp[8] = {(char)0}; char tmpExp[8] = {(char)0}; int exp1, exp2, i; // Split the result split(result, resMan, resExp); // Split x1, get exp1 split(x1, man1, tmpExp); exp1 = bin2dec(tmpExp); // Split x2, get exp2 split(x2, man2, tmpExp); exp2 = bin2dec(tmpExp); // Align the two mantissas int bigExp = align(exp1, man1, exp2, man2); // Write the result exponent dec2bin(bigExp, resExp); // Add the mantissas int tmp = 0; int rem = 0; for (i = 22; i >= 0; i--) { tmp = (int) man1[i] + (int) man2[i] + rem; if (tmp == 3) { rem = 1; resMan[i] = (char) 1; } else if (tmp == 2) { rem = 1; resMan[i] = (char) 0; } else if (tmp == 1) { rem = 0; resMan[i] = (char) 1; } else if (tmp == 0) { rem = 0; resMan[i] = (char) 0; } } // Gather the result result[0] = (char) 0; // Assuming always positive, as per the hw document gather(resMan, resExp, result); }
void f13_4() { PRINT_DEBUG_INFO(); for (int a=1;a<=10;a++) { cout<<"SPHERE_VOLUME("<<a<<")\t="<<SPHERE_VOLUME(a) <<"\t|\t"<<dec2bin(SPHERE_VOLUME(a))<<endl; if(SPHERE_VOLUME(a)<0) {break;} } cout<<dec2bin(1)<<endl; cout<<dec2bin(2)<<endl; cout<<dec2bin(4)<<endl; cout<<dec2bin(8)<<endl; cout<<dec2bin(7)<<endl; cout<<dec2bin(9)<<endl; }
//Puts in a set the union of all Zl(preds). Preds are all predecessors of "node" bool Signatures::getZlPred(Node *node, set<__uint64_t> *result){ SetNode preds = node->getPreds(); for(SetNode::iterator pred=preds.begin(); pred != preds.end(); pred++){ Node *nodePred = *pred; //None of predecessor may have EMPTY_SIGNATURE if(nodePred->getLowerNES()==EMPTY_SIGNATURE){ outs()<<"Empty signature error! Node: "<< node->getBB()->getName() << " Predecessor: "<<nodePred->getBB()->getName() <<"\n"; return false; }else{ //outs()<<"Node: "<< node->getBB()->getName() << " Predecessor: "<<nodePred->getBB()->getName() <<"\n"; string valStr = dec2bin(nodePred->getLowerNES()); set<__uint64_t> tmp = calcZl(nodePred->getLowerNES()); result->insert(tmp.begin(), tmp.end()); } } return true; }
int main() { int res, i, j, sum; int s[21] = {0}; sum = 0; for (i=1; i<LIMIT; i++) { res = checkPalindrome(i); if (res) { dec2bin(i, s); if (checkPalindromeBin(s)) { sum += i; } } } printf("sum is %d\n", sum); //872187 return 0; }
int validate(const char *goodip, const char *testip, int mask) { if(mask == 0) return 1; if(mask > 32) mask = 32; if(NULL == goodip || NULL == testip) return 0; int one; int two; int three; int four; char bin1[40]; char bin2[40]; char first[9]; char second[9]; char third[9]; char fourth[9]; //convert ip to bitstring sscanf(goodip, "%d.%d.%d.%d", &one, &two, &three, &four); dec2bin(one, first, 8); dec2bin(two, second, 8); dec2bin(three, third, 8); dec2bin(four, fourth, 8); sprintf(bin1, "%s%s%s%s", fourth, third, second, first); printf("good ip bitstring=%s\n", bin1); sscanf(testip, "%d.%d.%d.%d", &one, &two, &three, &four); dec2bin(one, first, 8); dec2bin(two, second, 8); dec2bin(three, third, 8); dec2bin(four, fourth, 8); sprintf(bin2, "%s%s%s%s", fourth, third, second, first); printf("test ip bitstring=%s\n", bin2); //compare ip address are backwards, check from end to begining int x = 0; for(; x < mask; ++x){ int index = 32 - x - 1; //mismatch if(bin1[index] != bin2[index]) return 0; } return 1; }
void convert(double x, char mantissa_exponent[]) { int i; char mantissa[23] = {(char)0}; char exponent[8] = {(char)0}; // Calculate sign bit first if (x < 0) { mantissa_exponent[0] = 1; x *= -1; } else mantissa_exponent[0] = 0; // Seperate the decimal and fractional parts int decPart = (int) x; double fracPart = x - decPart; // Conver the decimal part to binary, put it at the end of the array for (i = 0; decPart >= 1; i++) { mantissa[22-i] = (char) (decPart % 2); decPart = decPart / 2; } i--; int exp = i; // Shift mantissa to left 22-exp shiftl(mantissa, 22-exp); // Put exponent in mantissa_exponent array dec2bin(exp, exponent); // Deal with fractional part if (fracPart != 0.0) { i = exp+1; // Current position in mantissa for (; i < 32; i++) { fracPart = fracPart * 2; mantissa[i] = (char) ((int)fracPart); fracPart -= (int)fracPart; } } // Gather result gather(mantissa, exponent, mantissa_exponent); }
int main(int argc, char *argv[]) { if (argc < 2) { printf("Usage: %s <number>\n", argv[0]); return 1; } int a = atoi(argv[1]); printf("DEC: %d\n", a); printf("HEX: "); dec2hex(a); printf("BIN: "); dec2bin(a); printf("OCT: "); dec2radix(a, 8); printf("26: "); dec2radix(a, 26); return 0; }
static int roadmap_nmea_decode_coordinate (char *value, char *side, char positive, char negative) { /* decode longitude & latitude from the nmea format (ddmm.mmmmm) * to the format used by the census bureau (dd.dddddd): */ int result; char *dot = strchr (value, '.'); if (dot == NULL) { if (value[0] == 0) return 0; dot = value + strlen(value); } dot -= 2; result = 0; while (value < dot) { result = dec2bin(*value) + (10 * result); value += 1; } result *= TIGER_COORDINATE_UNIT; result += roadmap_nmea_decode_numeric (dot, TIGER_COORDINATE_UNIT) / 60; if (side[1] == 0) { if (side[0] == negative) { return 0 - result; } if (side[0] == positive) { return result; } } return 0; }
bool Signatures::calcd1d2(vector<Node*> vNodes){ for(int i =0 ; i < vNodes.size(); i++){ Node *node = vNodes[i]; __uint64_t d1 = 0; __uint64_t d2 = 0; //For each node N1, if N1 is of type A, the upper half of d1 is set to an all 1 pattern. //Its lower half is set equal to the lower half of NS(N1). if(node->getType() == typeA){ string lower = dec2bin(node->getLowerNS()); string d1Str = iniOnes+lower; d1 = bin2dec(d1Str);; node->setd1Value(d1); }else{ //if N1 is of type X. d1 = node->getSignature(); SetNode preds = node->getPreds(); __uint64_t tmpExit =0; if(!preds.empty()){ for(SetNode::iterator pred=preds.begin(); pred != preds.end(); pred++){ Node *nodePred = *pred; tmpExit = nodePred->getExitSignature() ; //outs()<<" Pred "<< nodePred->getBB()->getName()<<" type:"<< nodePred->getTypeStr()<<"\n"; break; } } d1 = d1^tmpExit; //xor node->setd1Value(d1); } d2 = node->getSignature() ^ node->getExitSignature(); node->setd2Value(d2); } return true; }
int main(int argc, char *argv[]) { FILE *fp; int c, i; char rbn[] = "0000000"; if(argc != 2) { printf("Usage: %s <file>\n", argv[0]); exit(EXIT_FAILURE); } errno = 0; fp = fopen(argv[1], "r"); if(fp == NULL) { fprintf(stderr, "%s: Couldn't open file %s; %s\n", argv[0], argv[1], strerror(errno)); exit(EXIT_FAILURE); } while((c = fgetc(fp)) != EOF) { dec2bin(c, rbn); #ifdef DEBUG fprintf(stderr, "%c: %d - b%s\n", c, c, rbn); #endif printf(" "); for(i = 6; i >= 0; i--) printf("%s", rbn[i] == '0' ? " " : "\t"); printf("\n\t\n "); strcpy(rbn, "0000000"); } printf("\n\n\n"); fclose(fp); exit(EXIT_SUCCESS); }
void itob(int n, char s[], int b) { switch (b) { case 2: dec2bin(n,s); printf("%s\n",s); break; case 8: dec2oct(n,s); reverse(s); printf("%s\n",s); break; case 10: printf("%d\n",n); break; case 16: dec2hex(n,s); reverse(s); printf("%s\n",s); break; default: break; } }
bmat int2bin::process(bvec ce, ivec x) { bmat y; int N; #if (DEBUG_LEVEL==3) cout << "***** int2bin::process *****" << endl; cout << "ce=" << ce << endl; cout << "x=" << x << endl; sleep(1000); #endif N=ce.length(); if (x.length()!=N) { throw sci_exception("int2bin::process - ce.size <> x.rows()", x.length() ); } y.set_size(N,symbol_size); for (int i=0; i<N; i++) { if ( bool(ce[i])) { y0 = dec2bin(symbol_size, x[i]); if (! msb_first) { y0 = reverse(y0); } } y.set_row(i,y0); } #if (DEBUG_LEVEL==3) cout << "y=" << y << endl; cout << "+++++ int2bin::process +++++" << endl; sleep(1000); #endif return (y); }
static int format_questions(const ocra_suite * ocra, uint8_t *out, const char *Q) { int l = 0; switch (ocra->Q_fmt) { case a: if (128 < (l = strlen(Q))) return RFC6287_INVALID_CHALLENGE; else memcpy(out, Q, l); break; case h: if (0 > (l = hex2bin(out, Q))) return l; break; case n: if (0 > (l = dec2bin(out, Q))) return l; break; } memset(out + l, 0, 128 - l); return RFC6287_SUCCESS; }
main() { srand(time(NULL)); FILE *fp; long long int i,j; int n; y=(int**)malloc(sizeof(int *)*2); for(i=0;i<2;i++) y[i]=(int*)malloc(sizeof(int)*2); A=(int**)malloc(sizeof(int *)*2); for(i=0;i<2;i++) A[i]=(int*)malloc(sizeof(int)*2); y[0][0]=1; y[0][1]=0; y[1][0]=0; y[1][1]=1; A[0][0]=1; A[0][1]=1; A[1][0]=1; A[1][1]=0; //fp=fopen("input.txt","w+"); /*for(i=0;i<1000;i++) { n=(int)rand()%10; n=n%10; fprintf(fp,"%d",n); } i=0; fseek(fp,0,SEEK_SET); while(!feof(fp)) { fscanf(fp,"%d",&n); N[i++]=n; }*/ i=0; printf("enter size"); scanf("%lld",&size_N); if(size_N<=0||size_N>100000) { printf("invalid size"); exit(0); } N[0]=(int)rand()%9+1; for(i=1;i<size_N;i++) { //fread(&n,sizeof(char),1,fp); //if(n>='0'&&n<='9') n=(int)rand()%10; N[i++]=n; } size_N=i; //for(i=0;i<size_N;i++) // printf("%d ",N[i]); dec2bin(N); //for(j=0;j<size_N;j++) // printf("%d ",N[j]); while(size_N>0) { if(N[size_N-1]==1) y=multiply(y,A); A=multiply(A,A); size_N=size_N-1; } printf("%d",y[1][0]); //fclose(fp); free(y); free(A); }
float ForcaBruta(float * pes, int n,float * val, float tamanhoMochila, int* back) { float maiorValor = 0,maiorPeso = 0; float w = tamanhoMochila; string escolha; long double num_combinacao = potencia(2,n); for(long double i = 0;i <= (num_combinacao);i++) { float somaPeso = 0, somaValor = 0 ; string valorBin; string atual; /** Inicio da conversão para bin */ //preenchendo o valor com '0' valorBin.insert(valorBin.begin(),n,'0'); dec2bin(i,valorBin); valorBin = string ( valorBin.rbegin(), valorBin.rend() ); size_t pos = valorBin.find_first_of('1'); if (pos != -1) { atual = valorBin.substr(pos); //somando os pesos itens escolhidos for(int ini = 0;ini<n;ini++){ if(valorBin[ini] == '1'){ somaPeso+=pes[ini]; somaValor+=val[ini]; } } if(((w - somaPeso) >= 0) && (somaValor > maiorValor)){ maiorValor = somaValor; maiorPeso = somaPeso; escolha = valorBin; } } /** Fim da conversão */ } float totalpeso = 0, totalvalor = 0; //cout << "\nValor" << setw(16) << "Peso " << endl; for(int y = 0;y < n;y++){ if(escolha[y] == '1'){ // int digitos = getDigitos(val[y]); // cout << '\n' << val[y] << setw(20 - digitos) << pes[y]; back[y] = 1; totalpeso += pes[y]; totalvalor += val[y]; } } return totalvalor; //cout << "\n\n"<<totalvalor << setw(20 - getDigitos(totalvalor)) << totalpeso << endl; }
void execute() { int i, dec_op, dec_ac, dec_arg; char op[OPCODE_SIZE+1], arg[MEM_WIDTH+1-OPCODE_SIZE]; //local vars declared for(i=0; i<OPCODE_SIZE; i++) op[i]=ir[i]; op[i+1]='\0'; //derives the OPCode from the first 3 bits in the IR, //which is derived from the current memory address, and //puts a null character at the end of op[] so that it can // be used as a string in bin2dec. for(i=OPCODE_SIZE; i<MEM_WIDTH+1; i++) arg[i]=ir[i]; //uses remaining 5 bits in memory to determine the //binary representation of the argument to be executed. dec_op=bin2dec(op); dec_ac=bin2dec(ac); dec_arg=bin2dec(arg); //initializes the decimal representation of binary numbers op, //ac, and arg, for later convenience. if(dec_op==0) halt=1; //if the OPCode codes for 0, halt is made true, and execute is done. //this causes a reaction in main(), in that the loop that //repeatedly checks memory for commands, executes, increments pc, //and checks again is broken. Memory and AC are displayed, and //main terminates. else if(dec_op==1) { if(dec_ac != 0) pc=dec_arg; } //performs JANZ for the OPCode 1. Jumps PC to memory address //in argument. else if(dec_op==2) { strcpy(memory[dec_arg],ac); } //performs StAM. copies current AC value to memory //address as speicified by memory[dec_arg]. else if(dec_op==3) { strcpy(ac, memory[dec_arg]); } //performs LdAM for OPCode 3. Copies memory value //memory[dec_arg] into the AC. else if(dec_op==4) { dec_ac=dec_ac+bin2dec(memory[dec_arg]); dec2bin(dec_ac, ac); } //performs AddM for OPCode 4. Adds the memory //at address arg to the AC. else if(dec_op==5) { dec_ac+=dec_arg; dec2bin(dec_ac,ac); } //performs AddI for OPCode 5. Adds the argument to //the AC. else if(dec_op==6) { dec_ac-=bin2dec(memory[dec_arg]); dec2bin(dec_ac,ac); } //performs SubM for OPCode 6. Subtracts memory at //address arg from the AC. else if(dec_op==7) { dec_ac-=dec_arg; dec2bin(dec_ac,ac); } //performs SubI for OPCode 7. Subtracts arg from the AC. }