Skip to content
This repository has been archived by the owner on Jul 5, 2022. It is now read-only.

Commit

Permalink
Transcribe Binary_To_Decimal to Processing.
Browse files Browse the repository at this point in the history
  • Loading branch information
FriskyDev committed Dec 31, 2018
1 parent 023037e commit e0686ec
Show file tree
Hide file tree
Showing 2 changed files with 100 additions and 0 deletions.
@@ -0,0 +1,58 @@
// Daniel Shiffman
// http://youtube.com/thecodingtrain
// http://codingtra.in
// Processing transcription: Chuck England

// Coding Challenge 120: Bit Shifting
// https://youtu.be/oCBlwsY8sR4

// p5.js editor version: 0.7.2 (December 21, 2018)
// https://editor.p5js.org/codingtrain/sketches/Hk8CVYvi7

String num = "10101001";
Bit[] byte_ = new Bit[8];

void setup() {
size(400, 200);
println(binaryToDecimal(num));
float w = width / 8;
for (int i = 0; i < 8; i++) {
byte_[i] = new Bit(w / 2 + i * w, 50, w - 4);
byte_[i].setState(num.charAt(i) == '1');
}
}

String getBinaryString() {
String num = "";
for (int i = 0; i < byte_.length; i++) {
byte_[i].show();
num += byte_[i].state ? "1" : "0";
}
return num;
}

void draw() {
background(51);

num = getBinaryString();

noStroke();
fill(255);
textSize(50);
text(Integer.toString(binaryToDecimal(num)), 10, 130);
}

void mousePressed() {
for (int i = 0; i < byte_.length; i++) {
byte_[i].toggle(mouseX, mouseY);
}
}

int binaryToDecimal(String val) {
int sum = 0;
for (int i = 0; i < val.length(); i++) {
String bit = String.valueOf(val.charAt(val.length() - i - 1));
sum += Integer.parseInt(bit) * pow(2, i);
}
return sum;
}
@@ -0,0 +1,42 @@
// Daniel Shiffman
// http://youtube.com/thecodingtrain
// http://codingtra.in
// Processing transcription: Chuck England

// Coding Challenge 120: Bit Shifting
// https://youtu.be/oCBlwsY8sR4

// p5.js editor version: 0.7.2 (December 21, 2018)
// https://editor.p5js.org/codingtrain/sketches/Hk8CVYvi7

class Bit {
float x;
float y;
float diameter;
Boolean state;

Bit(float x_, float y_, float d_) {
x = x_;
y = y_;
diameter = d_;
state = false;
}

void setState(Boolean state_) {
state = state_;
}

void toggle(float x, float y) {
float d = dist(x, y, this.x, this.y);
if (d < diameter / 2) {
state = !state;
}
}

void show() {
stroke(255);
strokeWeight(2);
fill(state ? color(0, 255, 0) : color(0));
ellipse(x, y, diameter, diameter);
}
}

0 comments on commit e0686ec

Please sign in to comment.