بسم الله الرحمن الرحيم ..
السلام عليكم و رحمة الله و بركاته ..
هالاسبوع كله يلست اشتغل على كود وااحد بس و ما رضى يضبط وياي..بعدي اول كورس أخذ فيه مساق جاافا :wacko:
هذا الكود يحول من الديسمل للباينري و العكس يعني من الباينري للديسمل
الميثود الاول يحول من الديسمل للباينري
و الميثود الثاني يحول من الباينري للديسمل
و المثود الثالث يعطينا السكند كومليمنت
و الميثود الرابع يعطينا الناتج اذا ادخلنا عدد ديسمل سالب او موجب و يحوله الى باينري باستخدام المثود الاول و الثالث
أما المثود الخامس ما عرفت اسويه :S
و هو اذا دخلنا عدد باينري يعطينا عدد ديسمل و نستخدم فيه المثود الثاني يعني يطبع لنا الناتج مثل الميثود الرابع
و هذا الكود اللي استخدمته
public class Converter
{
private int[] a;
public Converter() {
a = new int[8];// this is adecleration of integer Array.
}
public void DecToBin(int x) {//This method converts the number from decimal to binary
int D = a.length-1;
int B = 0;
if(x == 0) a[D] = 0;
else if(x == 1) a[D] = 1;
else{
for(int i=D; i>=0; i--) {
B = x%2;
a = B;
x = x/2;
}
}
}
public int BinToDec(int[] b) {//This method converts the number from binary to decimal.
int dec=0;
for (int i=0; i<b.length; i++) {
dec <<= 1; // shift content of dec 1 position to the left (actually a multiplication with 2)
dec += b; // add the 0 or 1
}
return dec;
}
public void twoComplements(int x) {//This method gives you the two complements of the number if it is negative
DecToBin(x);
for(int i=0; i<=7; i++) {
if(a == 0) a = 1;
else{
a = 0;
}
}
a[0] = a[0] + 1;
if(a[0] == 2) {
a[0] = 0;
for(int i=1; i<=7; i++) {
a = a + 1;
if(a == 1) {
break;
}
else a = 0;
}
}
for(int i=7; i>=0; i--) {
System.out.print(a);
}
}
public void mainconvertD2B(int x) {//This is the main method wich the user run to convert from decimal (negative or positive) to binary
if(x <= 255){
if(x >= 0){
DecToBin(x); // call method DecToBin
System.out.print(x + " is converted to: ");
for(int i=0; i<=7; i++){
System.out.print(a);
}
System.out.println();
}
else{
twoComplements(x);
System.out.print(x + " is converted to: ");
for(int i=0; i<=7; i++) {
System.out.print(a);
}
System.out.println();
}
}
else{
System.out.println("The decimal number should from 0 to 255");
}
}
}