8 bit full adder in Java - java

In 'eightbitfulladder' function,I am trying to complement the sumno which is the result of addition of a positive number and a negative number.I found out the number it is sending in the 'convertobyte' function is different from the sumno computed. This is wierd. Can someone explain me what is happening.
import static java.lang.Math.pow;
public class CAModifiedBoothsMultiplier {
public byte byteArrayTobyte(byte[] b) {
byte value = 0;
for (byte i = 0; i < 8; i++) {
value += (b[i] * (pow(2, i)));
}
return value;
}
public byte[] twosComplement(byte x) {
byte y = (byte) (~x + 1);
byte mask = 1;
mask = (byte) (mask << 7);
byte num[] = new byte[10];
byte i = 0, num1 = 0;
for (i = 0; i < 8; i++) {
if ((y & mask) == 0)
num1 = 0;
else
num1 = 1;
y = (byte) (y << 1);
num[i] = num1;
}
return num;
}
public byte[] saveByte(byte number) {
byte mask = 1;
mask = (byte) (mask << 7);
byte num[] = new byte[10];
byte num1 = 0;
byte i = 0;
for (i = 0; i < 8; i++) {
if ((number & mask) == 0)
num1 = 0;
else
num1 = 1;
number = (byte) (number << 1);
num[i] = num1;
}
return num;
}
public byte[] eightbitFullAdder(byte a, byte b, byte cin) {
byte sum = 0, temp1 = 0, cout = 0;
byte sumno[] = new byte[10];
byte ain[] = saveByte(a);
byte bin[] = new byte[10];
if (cin == 1) {
bin = twosComplement(b);
cin = 0;
} else {
bin = saveByte(b);
}
System.out.print("The number entered is, a :");
for (int i = 0; i < 8; i++) {
System.out.print(ain[i]);
}
System.out.println("\n");
System.out.print("The number entered is, b :");
for (int i = 0; i < 8; i++) {
System.out.print(bin[i]);
}
System.out.println("\n");
for (int i = 7; i >= 0; i--) {
temp1 = (byte) (ain[i] ^ bin[i]);
sum = (byte) (temp1 ^ cin);
sumno[i] = sum;
cout = (byte) ((ain[i] & bin[i]) | (cin & temp1));
if (i != 0)
cin = cout;
}
for (int i = 0; i < 8; i++) {
System.out.print(sumno[i]);
}
System.out.println("\n");
if (sumno[0] == 1) {
byte[] sumnocomp = new byte[10];
byte temp2 = 0;
temp2 = byteArrayTobyte(sumno);
System.out.print(temp2);
sumnocomp = twosComplement(temp2);
return sumnocomp;
} else {
return sumno;
}
}
public static void main(String args[]) {
CAModifiedBoothsMultiplier mbm = new CAModifiedBoothsMultiplier();
byte x = 5;
byte complementedno[];
complementedno = mbm.twosComplement(x);
for (int i = 1; i <= 8; i++)
System.out.print(complementedno[i]);
System.out.println("\n");
byte a = 6, b = 8, cin = 1;
byte fulladder[] = mbm.eightbitFullAdder(a, b, cin);
System.out.print("The sum of numbers entered is :");
for (int i = 0; i < 8; i++) {
System.out.print(fulladder[i]);
}
System.out.println("\n");
}
}

Related

Scramble each digit of the int a and print out the biggest possible integer

I’m stuck here. Do I just keep making new strings and turn them to int or us there a faster better way?
public void biggest(int a){
int random;
String aS = String.valueOf(a);
int ah=9;
if (a<10)
System.out.println(a);
for(int i= 0;i<aS.length();i++){
String firstNum = aS.substring(i,i+1);
for (int j = ah; j > Integer.parseInt(firstNum); j--){
System.out.println(ah);
}
}
} ```
public static int biggest(int num) {
if (num == 0)
return 0;
int res = 0;
if (num > 0) {
for (int i = 9; i >= 0; i--)
res = update(res, i, num);
} else {
for (int i = 0; i <= 9; i++)
res = update(res, i, num);
res *= -1;
}
return res;
}
private static int update(int res, int i, int n) {
n = Math.abs(n);
while (n > 0) {
if (n % 10 == i)
res = res * 10 + i;
n /= 10;
}
return res;
}
Output:
System.out.println(biggest(12341234)); // 44332211
System.out.println(biggest(-12341234)); // -11223344
There's no need to use conversion to String in this case, you can get the digits from the input number by getting a remainder by modulo 10, then dividing the input number by 10 and repeat it while the number > 0.
Each digit should be stored in an array or list.
To get the biggest number of these digits you should just sort them (standard facilities such as Arrays.sort or Collections.sort will do fine) and then "re-assemble" the biggest number from the lowest digit by multiplying it by 1, 10, 100, etc. and summing up.
So, plain implementation could be as follows:
public static int biggestPlain(int a) {
List<Integer> digits = new ArrayList<>();
while (a > 0) {
digits.add(a % 10);
a /= 10;
}
Collections.sort(digits);
int p = 1;
int num = 0;
for (int digit : digits) {
num += p * digit;
p *= 10;
}
return num;
}
Also, this task can be implemented using Stream API and lambda and applying the same approach:
public static int biggestStream(int a) {
AtomicInteger p = new AtomicInteger(1); // accumulate powers of 10
return IntStream.iterate(a, n -> n > 0, n -> n / 10) // divide input number by 10 while it > 0
.map(i -> (i % 10)) // get the digit
.sorted() // sort (the lower digits first)
.map(i -> p.getAndUpdate((x) -> x * 10) * i) // same as p * digit above
.sum(); // get the result number
}
Update
Iterate over digits from '9' till '0' and check if they are available in the string presentation of the input number.
String-based solution:
public static void biggest(int a) {
String aS = String.valueOf(a);
if (a < 10) {
System.out.println(a);
}
String num = "";
int count = 0;
out: for (char i = '9'; i >= '0'; i--) {
for (int j = 0; j < aS.length(); j++) {
char digit = aS.charAt(j);
if (digit == i) {
num += digit;
if (++count == aS.length()) {
break out;
}
}
}
}
System.out.println(num + " / " + Integer.parseInt(num));
}
Another option would be to count how many 0, 1, 2, ..., 9 values you have and then assemble them back together into a number knowing the digits will always be in descending order (9, 8, 7, ..., 0). The easy way to do this is with an array. Since this is a homework assignment the hard way (without using an array as per the requirement you added in a comment) is to use a variable counter per digit.
public class so64125767 {
public static int biggestBuckets(int a) {
int[] buckets = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
while (a > 0) {
buckets[a % 10]++;
a /= 10;
}
int num = 0;
for (int i = 9; i >= 0; i--) {
for (int j = 0; j < buckets[i]; j++) {
num *= 10;
num += i;
}
}
return num;
}
public static int biggestBucketsVar(int a) {
int zero = 0;
int one = 0;
int two = 0;
int three = 0;
int four = 0;
int five = 0;
int six = 0;
int seven = 0;
int eight = 0;
int nine = 0;
while (a > 0) {
switch (a % 10) {
case 0:
zero++;
break;
case 1:
one++;
break;
case 2:
two++;
break;
case 3:
three++;
break;
case 4:
four++;
break;
case 5:
five++;
break;
case 6:
six++;
break;
case 7:
seven++;
break;
case 8:
eight++;
break;
case 9:
nine++;
break;
}
a /= 10;
}
int num = 0;
for (int j = 0; j < nine; j++) {
num *= 10;
num += 9;
}
for (int j = 0; j < eight; j++) {
num *= 10;
num += 8;
}
for (int j = 0; j < seven; j++) {
num *= 10;
num += 7;
}
for (int j = 0; j < six; j++) {
num *= 10;
num += 6;
}
for (int j = 0; j < five; j++) {
num *= 10;
num += 5;
}
for (int j = 0; j < four; j++) {
num *= 10;
num += 4;
}
for (int j = 0; j < three; j++) {
num *= 10;
num += 3;
}
for (int j = 0; j < two; j++) {
num *= 10;
num += 2;
}
for (int j = 0; j < one; j++) {
num *= 10;
num += 1;
}
for (int j = 0; j < zero; j++) {
num *= 10;
// num += 0;
}
return num;
}
public static void main(String[] args) {
System.out.println(biggestBuckets(237428379));
System.out.println(biggestBucketsVar(237428379));
-- 987743322
}
}
I'm also going to bet if you benchmark these results along with the other suggestions (using String or Collections) you'll find this method scales the best (imagine if you accepted numbers beyond the size of an int).
String useMe = Integer.toString(argumentOne);
int rMe = argumentOne;
int x = 0;
while (x != 1000) {
int i = 0;
String returnMe = "";
String inUse = useMe;
while (i != useMe.length()) {
Random random = new Random();
int index = random.nextInt(inUse.length());
returnMe = returnMe + inUse.charAt(index);
inUse = inUse.substring(0, index) + inUse.substring(index + 1);
i++;
}
if (Integer.parseInt(returnMe) > rMe) {
rMe = Integer.parseInt(returnMe);
}
x++;
}
System.out.print( rMe );
}

padding to get 128 bits in java

import javax.swing.JOptionPane;
public class Stack {
static int count = 0;
static String res[] = new String[16];
public static void main(String[] args) {
String str = JOptionPane.showInputDialog("enter text");
String abc = "";
char[] messChar = str.toCharArray();
for (int i = 0; i < messChar.length; i++)
abc += Integer.toBinaryString(messChar[i]);
System.out.println(abc.length());
int leg = (int) ((abc.length() / 128) + 1);
String[] spl = new String[leg];
int j = 0, i;
for (i = 0; i < abc.length(); i++) {
if (count == 128) {
if (i == 128)
spl[j] = abc.substring(0, 128);
else
spl[j] = abc.substring(i - 128, i);
count = 0;
j++;
}
count++;
}
spl[j] = abc.substring(i - count, i);
for (int k = 0; k < spl.length; k++)
System.out.println(spl[k].length());
for (i = 0; i < spl.length; i++) {
String binary = spl[i];
System.out.println(binary);
}
}
}
The input for the above code is text. If I give some text, it converts it into binary and then splits it into 128 bits. But at last some bits are remaining which are less than 128 bits. However, I need exactly 128 bits. So how can I do padding to get 128 bits in Java? I am implementing the AES Algorithm 128 bit key.

printing the total value only one time without iteration

I want to print the statement System.out.println(sb.append(ss));
Only the last time I tried to take it out of the for loop but the result is wrong.
public static String constatmentvertBinaryStringToString(String string) {
StringBuilder sb = new StringBuilder();
char[] chars = string.toCharArray();
String ss = null;
//for each character
for (int j = 0; j < chars.length; j += 8) {
int idx = 0;
int sum = 0;
//for each bit in reverse
for (int i = 7; i >= 0; i--) {
if (chars[i + j] == '1') {
sum += 1 << idx;
}
idx++;
}
System.out.println(sum); //debug
int div = sum / 4;
System.out.println(div);
System.out.println((char) div);
int rem = sum % 4;
System.out.println(rem);
ss = (char) div + "" + rem;
System.out.println(sb.append(ss));
}
return sb.toString();
}
Put System.out.println(sb.append(ss)); out of the loop:
public static String constatment vertBinaryStringToString(String string){
StringBuilder sb = new StringBuilder();
char[] chars = string.toCharArray();
String ss=null;
//for each character
for (int j = 0; j < chars.length; j+=8) {
int idx = 0;
int sum =0;
//for each bit in reverse
for (int i = 7; i>= 0; i--) {
if (chars[i+j] == '1') {
sum += 1 << idx;
}
idx++;
}
System.out.println(sum); //debug
int div=sum/4;
System.out.println(div);
System.out.println((char)div);
int rem=sum%4;
System.out.println(rem);
ss=(char)div+""+rem;
}
System.out.println(sb.append(ss));
return sb.toString();
}
Because System.out.println(sb.append(ss)); contains a call to sb.append(ss)); taking the statement out of the for loop will have a different result than the one expected.
You should keep sb.append(ss); inside the loop and add System.out.println(sb) outside the loop.
public static String constatmentvertBinaryStringToString(String string) {
StringBuilder sb = new StringBuilder();
char[] chars = string.toCharArray();
String ss = null;
//for each character
for (int j = 0; j < chars.length; j += 8) {
int idx = 0;
int sum = 0;
//for each bit in reverse
for (int i = 7; i >= 0; i--) {
if (chars[i + j] == '1') {
sum += 1 << idx;
}
idx++;
}
System.out.println(sum); //debug
int div = sum / 4;
System.out.println(div);
System.out.println((char) div);
int rem = sum % 4;
System.out.println(rem);
ss = (char) div + "" + rem;
sb.append(ss);
}
System.out.println(sb);
return sb.toString();
}

Brute force own encryption in Java

I am writing a program for a class to first encrypt a string with a predetermined key. That part is done. Next part is where i have a problem or not a problem per se. its a question of redundancy. After this I am supposed to do a KPA on the string and the encrypted string to find the key.
Which is working but i am using like 15 nested for loops for the brute force. Is there another way to do this? without doing it recursively!
static String Key = null;
public static void main(String[] args) {
long startTime = System.nanoTime();
long startTime1 = System.currentTimeMillis();
int cntr = 0;
String key = "AAAAAAAAAAADDDAM";
String plaintext = "Secretfoemotherd";
StringBuilder cipher = new StringBuilder();
StringBuilder brutus = new StringBuilder();
byte[] ciphertext = encrypt(byteT(key), byteT(plaintext));
for (int i = 0; i < ciphertext.length; i++) {
cipher.append(ciphertext[i]);
}
while (true) {
char[] nkey = new char[16];
for (int i1 = 65; i1 < 122; i1++) {
nkey[0] = (char) i1;
for (int i2 = 65; i2 < 122; i2++) {
nkey[1] = (char) i2;
for (int i3 = 65; i3 < 122; i3++) {
nkey[2] = (char) i3;
for (int i4 = 65; i4 < 122; i4++) {
nkey[3] = (char) i4;
for (int i5 = 65; i5 < 122; i5++) {
nkey[4] = (char) i5;
for (int i6 = 65; i6 < 122; i6++) {
nkey[5] = (char) i6;
for (int i7 = 65; i7 < 122; i7++) {
nkey[6] = (char) i7;
for (int i8 = 65; i8 < 122; i8++) {
nkey[7] = (char) i8;
for (int i9 = 65; i9 < 122; i9++) {
nkey[8] = (char) i9;
for (int i10 = 65; i10 < 122; i10++) {
nkey[9] = (char) i10;
for (int i11 = 65; i11 < 122; i11++) {
nkey[10] = (char) i11;
for (int i12 = 65; i12 < 122; i12++) {
nkey[11] = (char) i12;
for (int i13 = 65; i13 < 122; i13++) {
nkey[12] = (char) i13;
for (int i14 = 65; i14 < 122; i14++) {
nkey[13] = (char) i14;
for (int i15 = 65; i15 < 122; i15++) {
nkey[14] = (char) i15;
for (int i16 = 65; i16 < 122; i16++) {
nkey[15] = (char) i16;
cntr++;
byte[] brutusCipher = Crack(
byteC(nkey),
byteT(plaintext));
for (int k = 0; k < brutusCipher.length; k++) {
brutus.append(brutusCipher[k]);
}
if (brutus
.toString()
.equals(cipher
.toString())) {
System.out
.println("found it");
System.out
.println("Key: "
+ Key);
System.out
.println("Brutus: "
+ brutus);
System.out
.println("i ran: "
+ cntr
+ "times");
long endTime = System
.nanoTime();
System.out
.println("time:"
+ (endTime - startTime)
+ " ns");
long endTime1 = System
.currentTimeMillis();
System.out
.println("Took "
+ (endTime1 - startTime1)
+ " ms");
return;
}
brutus.setLength(0);
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
public static byte[] byteT(String s) {
return s.getBytes();
}
public static byte[] byteC(char[] s) {
StringBuilder temp = new StringBuilder();
for (int i = 0; i < s.length; i++) {
temp.append(s[i]);
}
Key = temp.toString();
return temp.toString().getBytes();
}
public static byte[] encrypt(byte[] key, byte[] plaintext) {
byte[] d = new byte[key.length];
System.out.println(key.length);
for (int i = 0; i < key.length; i++) {
d[i] = (byte) (key[i] ^ plaintext[i]);
}
return d;
}
public static byte[] Crack(byte[] key, byte[] plaintext) {
byte[] n = new byte[key.length];
for (int i = 0; i < key.length; i++) {
n[i] = (byte) (key[i] ^ plaintext[i]);
}
return n;
}
}
Here is my suggestion on how you can improve your code:
char[] nkey = new char[16];
for (int i =0 ;i<16;++i) {
nkey[i] = 65;
}
while (true) {
//... do the stuff you do in the inner of the cycle
int index = 15;
nkey[index]++;
while (index >= 0 && nkey[index] >= 122) {
nkey[index] = 65;
index--;
if (index < 0) {
break;
}
nkey[index]++;
}
}
You can imagine what I do as representing what you iterate upon as a number in base 122-65 and adding one to it.
You could create a class like this (not tested):
class IncrementableCharArray {
private final char[] array;
IncrementableCharArray(int size) {
array = new char[size];
Arrays.fill(array, 'A');
}
boolean increment() {
//here logic to increment the array
int index = 0;
while(index < array.length && array[index] == 'z') index++;
if (index == array.length) return false;
array[index]++;
return true;
}
char[] get() { return array; }
}
The performance won't be better but it will be a little bit more readable. And you can use it like this:
IncrementableCharArray array = new IncrementableCharArray(16);
while(array.increment()) {
char[] nkey = array.get();
//your test here
}

Convert byte to int and vice-versa

Anyone know how can I convert a large array of bytes, ex 1000 bytes into an int/long etc in java?
You can use a loop
byte[] bytes =
int[] ints = new int[bytes.length];
for(int i=0;i<bytes.length;i++)
ints[i] = bytes[i];
A 1000 elements might take up to 10 micro-seconds this way.
To convert a byte to an int in Java, you have two options:
byte val = 0xff;
int a = val; // a == -1
int b = (val & 0xff); // b == 0xff
There is no method in the Java library to convert an array from one primitive type to another, you'll have to do it manually.
Thanks Paŭlo. Here's the corrected answer:
public class Main {
public static int[] convert(byte[] in) {
int bytesPerSample = 4;
int[] res = new int[in.length / bytesPerSample];
for (int i = 0; i < res.length; i++) {
int bOffset = i * bytesPerSample;
int intVal = 0;
for (int b = 0; b < bytesPerSample; b++) {
int v = in[bOffset + b];
if (b < bytesPerSample - 1) {
v &= 0xFF;
}
intVal += v << (b * 8);
}
res[i] = intVal;
}
return res;
}
public static byte[] convert(int[] in) {
int bytesPerSample = 4;
byte[] res = new byte[bytesPerSample * in.length];
for (int i = 0; i < in.length; i++) {
int bOffset = i * bytesPerSample;
int intVal = in[i];
for (int b = 0; b < bytesPerSample; b++) {
res[bOffset + b] = (byte) (intVal & 0xFF);
intVal >>= 8;
}
}
return res;
}
public static void main(String[] args) {
int[] in = {33, 1035, 8474};
byte[] b = convert(in);
int[] in2 = convert(b);
System.out.println(Arrays.toString(in2));
}
}

Categories