/*
Store the length defining part of PBF into the output character array
PARAMETERS: len - the length of data part
            output - output character array
RETURN: the number of characters stored
*/
int storeLen(int len, char *output) {
    int parts = len/7 + 1, remainder, i, counter = 0;

    //except the last 3-bits part, all the other parts should be "111"
    for (i = parts; i > 1; i--) {
        sprintf(output, "111");
        counter += 3;
    }

    //now the last 3-bits part
    remainder = len % 7;
    remainder = intToBin(remainder);

    if ( 0 <= remainder && remainder < 10) {
        sprintf(output+counter, "00");
        counter += 2;
        sprintf(output+counter, "%d", remainder);
        counter += 1;
    } else if ( 10 <= remainder && remainder < 100) {
        sprintf(output+counter, "0");
        counter += 1;
        sprintf(output+counter, "%d", remainder);
        counter += 2;
    } else if ( 100 <= remainder && remainder < 1000) {
        sprintf(output+counter, "%d", remainder);
        counter += 3;
    } else {
        fprintf(stderr, "error occurs in storeLen funciton, remainder = %d", remainder);
        EXIT_FAILURE;
    }

    return counter;
}
示例#2
0
void Clock::init()
{
    setWindowIcon(QIcon(":/images/colors.png"));

    readSettings();
    m_backBrush.setStyle(Qt::SolidPattern);
    m_foreBrush.setStyle(Qt::SolidPattern);
    for (int i = 0; i < 10; ++i)
    {
        binaryNumbers[i] = intToBin(i);
    }
    setDateTimeSections(m_dateSections, m_timeSections);

    timer.setInterval(m_updateInterval);
    timerEvent();
    timer.start();
    connect(&timer, SIGNAL(timeout()), this, SLOT(timerEvent()));

    setMouseTracking(true);

    initMenu();
    settingsDlg = 0;

    alwaysOnTopAct->setChecked(m_isAlwaysOnTop);
    setAlwaysOnTop();
}
示例#3
0
string outArvore(vector <Symbol> symbols, string encoded, string *code)
{
    string outBin = "", c1 = "", c2 = "";
    *code = symbols.front().getCode();
    short unsigned index = 0;
    
    while (index < symbols.size() - 1)
    {
        c1 = symbols[index].getCode(); // Codigo do elemento mais significativo
        c2 = symbols[index+1].getCode(); // Codigo do segundo elemento mais significativo
        
        index++;
        
        int i = 0;
        while (c1[i] == c2[i]) // Enquanto os bits de dois simbolos vizinhos forem iguais
            i++;
        
        c2.erase(0,i); // Remova os i bits iguais entre os dois simbolos
        
        (*code) += c2; // Adicione o resto ao codigo da arvore
    }
    
    *code += '1'; // Adiciona-se o bit 1 para finalizar a representação da arvore
    
    outBin = *code; 
    
//    code.clear();
    c1.clear();
    c2.clear();
    
    for (short i = 0; i < symbols.size(); i++)
    {
        c1 = intToBin((unsigned char) symbols[i].getCharacter()); // Transforma o codigo ASCII do simbolo em binario
        fill(&c1, 8-c1.size()); // Aumenta a quantidade de bits do codigo para um byte
        outBin += c1; // Adiciona-se o codigo de cada simbolo
    }
    
    c1.clear();
    outBin += encoded; // Adiciona-se a mensagem codificada em Shannon-Fano
    
    encoded.clear();
    
    index = 0;
    
    while (index + 8 < outBin.size())
    {
        c1.assign(outBin, index, 8); // Atribui a substring de text com tamanho 8 começando de j
        outBin.erase(index,8);
        c2 += (char) binToInt(c1); // Transforma a string binaria bite em um numero inteiro
    }

    c1.assign(outBin, index, 8);
    
    c2 += (char) binToInt(c1);
    
    c2 += (char) c1.size();
    
    return c2;
}
/*
Convert an integer into Peter's Binary Form, and stores the binary form into a charater array with each character storing one bit of information.
Peter's Binary Form is composed of two parts.
The length defining part is initially 3 bits, specifying the length of the data part. If the 3 bits are all 1 (i.e. the length is equal to or greater than 7), another 3 bits are added. The rule applies for the subsequent 3-bits parts. The value is read as the sum of all the 3-bits part.
The data part stores the binary form of the integer.
NOTE: if the integer is 0, it will be stored as 000, no data part will be stored

PARAMETERS: input - integer to be converted
            output - character array used to store PBF
            outputLimit - the size of the character array

RETURN: the total number of bits of the Peter's Binary Form
*/
int intToPBF(int input, char *output, int outputLimit) {
    if (input == 0) {
        sprintf(output, "000");
        return 3;
    }

    unsigned bin, counter;
    bin = intToBin(input);

    //get the length of the binary number
    int length = sprintf(output, "%d", bin);

    counter = storeLen(length, output);

    if (counter + length > outputLimit) {
        fprintf(stderr, "PBFLIMIT too small");
        EXIT_FAILURE;
    }

    counter += storeData(bin, output+counter);
    return counter;
}
示例#5
0
文件: LP.c 项目: MarcusxDM/PaiDePiper
void decompress()
{
    FILE * file = fopen("compressed.txt","r");
    if (file == NULL)
    {
        printf ("ERROR 404: FILE NOT FOUND\n");
        exit(0);
    }
    int htLines,i,nmbChar,j;
    unsigned char Char;
    char bits[MAX_SIZE_BINARY_ARRAY];
    Hashtable * ht = createHashtable();
    unsigned Char2;
    char binaryText[MAX_SIZE_BINARY_ARRAY];
    fscanf(file,"%d",&htLines);//QUANTAS LINHAS SERÃO INSERIDAS NA HASH
    fgetc(file);
    for(i=0;i<htLines;++i)
    {
        Char = fgetc(file);
        fgetc(file); // PULAR O ESPAÇO ENTRE O CARACTER E OS BITS
        fgets(bits,MAX_SIZE_BINARY,file);
        bits[strlen(bits) - 1] = '\0'; // REMOVENDO \N QUE O FGETS COLOCA.
        put(ht,Char,Char,bits,0);
    }
    fscanf(file,"%d",&nmbChar);//PEGA QUANTOS CARACTERES TEM NA COMPRESSÃO
    fgetc(file);
    FILE* decomp = fopen("decomp.txt","w");
    do
    {
        Char = fgetc(file);
        if(Char == UNSIGNED_EOF)
        {
            break;
        }
        char binaryText[MAX_SIZE_BINARY_ARRAY];
        int * binary;
        binary = intToBin(Char);
        for(i=0;i<8;i++)
        {
            binaryText[i] = binary[i] + 48;
        }
        binaryText[8] = '\0';
        fprintf(decomp,"%s",binaryText);

    }
    while(Char != UNSIGNED_EOF);
    fclose(decomp);
    decomp = fopen("decomp.txt","r");
    FILE * decompressed = fopen("decompressed.txt","w");
    for(i=0;i<nmbChar;)
    {
        for(j=0;j<MAX_SIZE_BINARY;j++)
        {
            binaryText[j] = fgetc(decomp);
            binaryText[j+1] = '\0';
            unsigned char charByBit = getByBits(ht,binaryText);
            if(charByBit != UNSIGNED_EOF)
            {
                i++;
                fprintf(decompressed,"%c",charByBit);
                break;
            }
        }

    }

    removeht(ht);
    fclose(decompressed);
    fclose(file);
    fclose(decomp);
    remove("decomp.txt");
}
/*
Convert a decimal integer into its binary form, stored still as a decimal integer
*/
unsigned intToBin(unsigned k) {
    if (k == 0) return 0;
    if (k == 1) return 1;
    return (k % 2) + 10 * intToBin(k / 2);
}
  bool cwagmSegmentationEvaluation::phenotypeToChromosome(
                                         const functor::parameters& phenotype,
                                         chromosome& genotype) const {
    
    genotype.resize(bits::total());

    const parameters& par = getParameters();
    const cwagmSegmentation::parameters* phen =
      dynamic_cast<const cwagmSegmentation::parameters*>(&phenotype);

    if (isNull(phen)) {
      return false;
    }

    int pos=0;
    int ires;
    
    // median kernel size
    pos = intToBin((phen->medianParam.kernelSize-1)/2,pos,bits::MedianKernel,
                   (par.minValues.medianParam.kernelSize-1)/2,
                   (par.maxValues.medianParam.kernelSize-1)/2,
                   genotype);

    // color splitter
    if (phen->colorSplitter.find("XYZ") != std::string::npos) {
      ires=1;
    } else if (phen->colorSplitter.find("xyY") != std::string::npos) {
      ires=2;
    } else if (phen->colorSplitter.find("Luv") != std::string::npos) {
      ires=3;
    } else if (phen->colorSplitter.find("rgI") != std::string::npos) {
      ires=4;
    } else if (phen->colorSplitter.find("YUV") != std::string::npos) {
      ires=5;
    } else if (phen->colorSplitter.find("YIQ") != std::string::npos) {
      ires=6;
    } else if (phen->colorSplitter.find("OCP") != std::string::npos) {
      ires=7;
    } else { // (phen->colorSplitter.find("RGB")!=std::string::npos)
      ires=0; // RGB
    } 
    
    pos = intToBin(ires,pos,bits::ColorSplitter,0,7,genotype);

    // gradient kernel type
    ires = static_cast<int>(phen->colorContrastParam.kernelType);
    pos = intToBin(ires,pos,bits::GradientType,0,7,genotype);

    // gradient contrast format
    ires = static_cast<int>(phen->colorContrastParam.contrastFormat);
    pos = intToBin(ires,pos,bits::ContrastFormat,0,3,genotype);

    // watershed
    
    // neighborhood
    pos = intToBin((phen->watershedParam.neighborhood8) ? 1 : 0,
                   pos,bits::WatershedNeighborhood,
                   (par.minValues.watershedParam.neighborhood8) ? 1 : 0,
                   (par.maxValues.watershedParam.neighborhood8) ? 1 : 0,
                   genotype);

    // WatershedThreshold
    pos = intToBin(phen->watershedParam.threshold,
                   pos,bits::WatershedThreshold,
                   par.minValues.watershedParam.threshold,
                   par.maxValues.watershedParam.threshold,genotype);

    // minProbForWatershedThreshold
    pos = doubleToBin(phen->minProbForWatershedThreshold,
                      pos,bits::WatershedMinProbThreshold,
                      par.minValues.minProbForWatershedThreshold,
                      par.maxValues.minProbForWatershedThreshold,genotype);

    // harisRegionMergeParam.mergeThreshold
    pos = doubleToBin(phen->harisRegionMergeParam.mergeThreshold,
                      pos,bits::WatershedHarisMerge,
                      par.minValues.harisRegionMergeParam.mergeThreshold,
                      par.maxValues.harisRegionMergeParam.mergeThreshold,
                      genotype);

    // neighborhood
    pos = intToBin(static_cast<int>(phen->harisRegionMergeParam.mergeMode),
                   pos,bits::WatershedHarisMergeMode,
               static_cast<int>(par.minValues.harisRegionMergeParam.mergeMode),
               static_cast<int>(par.maxValues.harisRegionMergeParam.mergeMode),
                   genotype);

    // harisRegionMergeParam.minRegionNumber
    pos = doubleToBin(double(phen->harisRegionMergeParam.minRegionNumber),
                      pos,bits::WatershedHarisMinNumRegions,
                      par.minValues.harisRegionMergeParam.minRegionNumber,
                      par.maxValues.harisRegionMergeParam.minRegionNumber,
                      genotype);

    assert (pos == bits::total());
    
    return true;
    
  }
示例#8
0
文件: main.c 项目: modalpdx/dec2hex
// ----------------------------------------- 
// main function
// -----------------------------------------
//
// Input:
//   none
//
// Returns:
//   0/1 - success/failure
//
// Notes:
//   - character input is not handled yet.
// 
int main(void)
{
  int  idx;                      // general purpose index
  int  inputIdx;                 // index specific to stepping through user input 
  int  littleEndian = 0;         // flag for little endian: 0 = false, 1 = true
  int  jump;                     // amount to jump when parsing user input string
  int  decimalNumber;            // final integer to convert
  long long inputDecimalNumber;  // temp placeholder for value to convert 

  char ch, scrap;                // holds prompt for little endian conversion + stdin flush

  char decIntBits[INTBITS + 1];  // holds bits that describe decimal integer
  char hexBits[HEXINTBITS + 1];  // holds hex value for decIntBits[]

  char promptString[] = "Enter a number (0 to cancel): "; 

  int  maxchars = 100;           // maximum number of characters in user input
  char inputNumbers[maxchars];   // holds user input


  // Prompt for big endian or little endian output
  //
  printf("Byte ordering is set to big endian. Switch to little endian? (Y = yes): ");
  scanf(" %c", &ch);
  while ((scrap = getchar()) != '\n' && scrap != EOF);  // flush stdin
  if(tolower(ch) == 'y')
  {
      littleEndian = 1;
      printf("Byte order: little-endian\n");
  }
  else
  {
      printf("Byte order: big-endian\n");
  }


  // Prompt for a number. Loop until we get a number we can use, then
  // display the binary number and break the loop.
  //
  while(1 && (inputDecimalNumber != 0))
  {
      printf("\n%s", promptString);

      if(fgets(inputNumbers, sizeof(inputNumbers), stdin) != NULL)  // no valid characters input?
      {
          for(inputIdx = 0; (sscanf(&inputNumbers[inputIdx], "%25lld%n", &inputDecimalNumber, &jump) != EOF) && (jump <= maxchars); inputIdx += jump)
          {
              // If the number entered was outside the min/max range of regular integers...
              //
              if( inputDecimalNumber < INT_MIN || inputDecimalNumber > INT_MAX )
              {
                  printf("Number is outside of integer range (%d to %d).\n", INT_MIN, INT_MAX);
              }
              // If we get this far, we have a valid number. Convert it, then
              // display it and break from the while loop.
              //
              else if( inputDecimalNumber != 0 )
              {
                  decimalNumber = (int)inputDecimalNumber;   // convert input number to normal int
                  intToBin(decimalNumber, decIntBits);       // convert int to binary


                  // print the integer being converted
                  //
                  printf("%10d ", decimalNumber);

                  // convert to little endian byte ordering if requested
                  //
                  if(littleEndian == 1)
                  {
                      toLittleEndian(decIntBits);
                  }

          
                  // convert final bit array to hex
                  //
                  idx = 0;
                  while(idx < HEXINTBITS)
                  {
                      hexBits[idx++] = '0';                      
                  }

                  binToHex(decIntBits, hexBits);             // convert to hex
                  printf("0x");                              // start the hex string


                  // display the hex string
                  //
                  idx = 0;
                  while(idx < strlen(hexBits))
                  {
                      printf("%c", hexBits[idx]);
                      idx++;
                  }
                  printf("\n");
              }
          }
      }
      else
      {
          break;
      }
  }

  return 0;

} // end of main()