Pages

vendredi 12 juin 2015

integer to binary

// Learning Processing

int[] input = new int[10];

PFont f;

// Variable to store text currently being typed
String typing = "";

// Variable to store saved text when return is hit
String int2b = "";
// Variable to store saved text when return is hit
String int2H = "";


void setup() {
  size(300,200);
  f = createFont("Arial",16,true);
 int[] input = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
}

void draw() {
  background(255);
  int indent = 25;
  
  // Set the font and fill for text
  textFont(f);
  fill(0);
  
  // Display everything
  text("entrez un nombre decimal ! ", 40, indent);
  text(typing,indent,90);
  text(int2b,indent,130);
  text(int2H,indent,170);
}

/*
void keyPressed() {
  // If the return key is pressed, save the String and clear it
  if (key == '\n' ) {
    saved = binary(parseInt(typing),8);
    // A String can be cleared by setting it equal to ""
    typing = ""; 
  } else if ( 47<keyCode && keyCode<58) {
    // Otherwise, concatenate the String
    // Each character typed by the user is added to the end of the String variable.
    typing = typing + key; 
  }
}


void keyPressed()
{
  switch (key) {// 
    case '\n':
      int2b = typing + " > " + binary(parseInt(typing),8);
      int2H = typing + " > " + hex(parseInt(typing),8);
    // A String can be cleared by setting it equal to ""
      typing = ""; 
      break;
    case '0':
    case '1':    
    case '2':
    case '3':    
    case '4':
    case '5':    
    case '6':
    case '7':    
    case '8':
    case '9':
    typing = typing + key; 
      break;     
    default: 
      break;
  }
}

*/

static final int digitToNum(char ch) {
  print(ch);
  int num = ch - '0';
  println(num);
  return num >= 0 & num <= 9 ? num : -1;
}

void keyPressed() {
  

  
  // If the return key is pressed, save the String and clear it
  if (key == '\n' ) {
      int2b = typing + " = " + binary(parseInt(typing),8);
      int2H = typing + " = " + hex(parseInt(typing),8);
    // A String can be cleared by setting it equal to ""
    typing = ""; 

  } else if ( digitToNum(key) > 0 ) {

    // Otherwise, concatenate the String
    // Each character typed by the user is added to the end of the String variable.
    typing = typing + key; 
  }
}