Skip to content

Instantly share code, notes, and snippets.

@tkaczenko
Created October 15, 2016 09:03
Show Gist options
  • Save tkaczenko/c35fff6ceda5132e9e09ff31d2fcaf5e to your computer and use it in GitHub Desktop.
Save tkaczenko/c35fff6ceda5132e9e09ff31d2fcaf5e to your computer and use it in GitHub Desktop.
Utility classes are written in Java for converting to binary, hex, octal and addition, subtraction using algorithms.

Example of using:

Please, write numbers: 
20161014 19970613
199706.13
Binary
Binary A:					Binary B:
01001100111010000111110110	01001100001011101000110101
Decimal A:					Decimal B:
20161014					19970613
Substract:					Decimal
000000000101110011111000001	190401

Hexadecimal
Hex A:			Hex B:
133A1F6			130BA35
Decimal A:		Decimal B:
20161014		19970613
Substract:		Decimal
002E7C1			190401

Octal
Oct A:			Oct B:
114720766		114135065
Decimal A:		Decimal B:
20161014		19970613
Substract:		Decimal
000563701		190401

Float to binary: 0110000110000011010.001000010100011110101110000101001
package converter;
/**
* Class utility for converting numbers to binary and back
* Addition and subtraction works for positive numbers
* Converter works right. Converter use two's complement for negative numbers
* <b>Functions:</b>
* <ul>
* <li>Converting integer to binary string</li>
* <li>Converting floating point (double) to binary string</li>
* <li>Addition binary string numbers</li>
* <li>Subtraction binary string numbers</li>
* </ul>
*
* @author tkaczenko
* @see <a href="https://en.wikipedia.org/wiki/Two%27s_complement">https://en.wikipedia.org/wiki/Two%27s_complement</a>
*/
public class Binary {
/**
* Addition for binary string numbers
*
* @param s1 Binary string created with {@code Binary}
* @param s2 Binary string created with {@code Binary}
* @return Binary string as a result of addition
*/
public static String addition(String s1, String s2) {
if (s1 == null || s2 == null) return "";
// Addition algorithm for binary numbers
int first = s1.length() - 1;
int second = s2.length() - 1;
StringBuilder sb = new StringBuilder();
int carry = 0;
while (first >= 0 || second >= 0) {
int sum = carry;
if (first >= 0) {
sum += s1.charAt(first) - '0';
first--;
}
if (second >= 0) {
sum += s2.charAt(second) - '0';
second--;
}
carry = sum >> 1;
sum = sum & 1;
sb.append(sum == 0 ? '0' : '1');
}
if (carry > 0) {
sb.append('1');
}
sb.reverse();
/// FIXME: 15.10.16 Fix subtraction for positive and negative numbers using addition
// Only for subtraction positive number
if (s1.charAt(0) == '1' && s2.charAt(0) == '1') {
sb.setCharAt(0, '1');
} else {
sb.setCharAt(0, '0');
}
return sb.toString();
}
/**
* Subtraction for binary string numbers
*
* @param s1 Binary string created with {@code Binary}
* @param s2 Binary string created with {@code Binary}
* @return Binary string as a result of subtraction
*/
public static String subtraction(String s1, String s2) {
// Change sign of second number to use addition
char c = (s2.charAt(0) == 1) ? '0' : '1';
s2 = c + s2.substring(1);
return addition(getTwosComplement(s1), getTwosComplement(s2));
}
public static String toBinary(double n) {
String decimal = toBinary((int) n);
double fraction = n - ((int) n);
String val = decimal + ".";
if (fraction < 0) {
val += "0";
}
while (fraction > 0) {
double r = fraction * 2;
if (r >= 1) {
val += "1";
fraction = r - 1;
} else {
val += "0";
fraction = r;
}
}
return val;
}
public static String toBinary(int num) {
StringBuilder stringBuilder = new StringBuilder();
boolean isNegative = (num < 0);
if (isNegative) {
num = Math.abs(num);
}
while (num > 0) {
stringBuilder.insert(0, num & 1);
num >>= 1;
}
// If number < 7 add zero and next add sign cell
for (int i = stringBuilder.length() - 1; i < 7; i++) {
stringBuilder.insert(0, "0");
}
if (isNegative) {
stringBuilder.insert(0, "1");
} else {
stringBuilder.insert(0, "0");
}
if (stringBuilder.length() == 0) {
stringBuilder.append("0");
}
return stringBuilder.toString();
}
public static int toDecimal(String str) {
double val = 0;
int k = 1;
if (str.charAt(0) == '1') {
k = -1;
}
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i) == '1') {
val += Math.pow(2, str.length() - 1 - i);
}
}
val *= k;
return (int) val;
}
/**
* Get two's complement for binary negative number
*
* @param binaryInt Binary string created with {@code Binary}
* @return String of two's complement
*/
private static String getTwosComplement(String binaryInt) {
if (binaryInt.charAt(0) == '1') {
String invertedInt = invertDigits(binaryInt);
return addition(invertedInt, "1");
} else {
return binaryInt;
}
}
private static String invertDigits(String binaryInt) {
StringBuilder stringBuilder = new StringBuilder(binaryInt);
for (int i = 1; i < stringBuilder.length(); i++) {
if (stringBuilder.charAt(i) == '1') {
stringBuilder.setCharAt(i, '0');
} else {
stringBuilder.setCharAt(i, '1');
}
}
return stringBuilder.toString();
}
}
package converter;
/**
* Class utility for converting numbers to hexadecimal and back
* Addition and subtraction works, but I'm not sure that It works right always
* Converter works right.
* <b>Functions:</b>
* <ul>
* <li>Converting integer to hex string</li>
* <li>Addition hex string numbers</li>
* <li>Subtraction hex string numbers</li>
* </ul>
*
* @author tkaczenko
*/
public class Hexadecimal {
private static String digits = "0123456789ABCDEF";
public static String addition(String s1, String s2) {
if (s1 == null || s2 == null) return "";
int first = s1.length() - 1;
int second = s2.length() - 1;
StringBuilder sb = new StringBuilder();
int carry = 0;
while (first >= 0 || second >= 0) {
int sum = carry;
if (first >= 0) {
sum += digits.indexOf(s1.charAt(first));
first--;
}
if (second >= 0) {
sum += digits.indexOf(s2.charAt(second));
second--;
}
carry = sum >> 4;
sum = sum & 0x0F;
sb.append(sum);
}
if (carry > 0)
sb.append(carry & 0x0F);
sb.reverse();
return sb.toString();
}
public static String subtraction(String s1, String s2) {
if (s1 == null || s2 == null) return "";
int first = s1.length() - 1;
int second = s2.length() - 1;
StringBuilder sb = new StringBuilder();
int carry = 0;
while (first >= 0 || second >= 0) {
int sub = carry;
if (first >= 0) {
sub += digits.indexOf(s1.charAt(first));
first--;
}
if (second >= 0) {
sub -= digits.indexOf(s2.charAt(second));
second--;
}
carry = sub >> 4;
sub = sub & 0x0F;
sb.append(digits.charAt(sub));
}
if (carry > 0)
sb.append(digits.charAt(carry & 0x0F));
sb.reverse();
return sb.toString();
}
public static String toHex(int num) {
StringBuilder stringBuilder = new StringBuilder();
while (num > 0) {
int j = num & 0x0F;
stringBuilder.insert(0, digits.charAt(j));
num >>= 4;
}
return stringBuilder.toString();
}
public static int toDecimal(String str) {
str = str.toUpperCase();
double val = 0;
for (int i = 0; i < str.length(); i++) {
val += Math.pow(16, str.length() - 1 - i) * digits.indexOf(str.charAt(i));
}
return (int) val;
}
}
package com.company;
import converter.Binary;
import converter.Hexadecimal;
import converter.Octal;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Please, write numbers: ");
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
double num = scanner.nextDouble();
scanner.close();
System.out.println("Binary");
String binaryA = Binary.toBinary(a);
String binaryB = Binary.toBinary(b);
int decimalA = Binary.toDecimal(binaryA);
int decimalB = Binary.toDecimal(binaryB);
System.out.println("Binary A:\t\t\t\t\tBinary B:");
System.out.println(binaryA + "\t" + binaryB);
System.out.println("Decimal A:\t\t\t\t\tDecimal B:");
System.out.println(decimalA + "\t\t\t\t\t" + decimalB);
String res = Binary.subtraction(binaryA, binaryB);
System.out.println("Substract:\t\t\t\t\tDecimal");
System.out.println(res + "\t" + Binary.toDecimal(res));
System.out.println("\nHexadecimal");
String hexA = Hexadecimal.toHex(a);
String hexB = Hexadecimal.toHex(b);
int decA = Hexadecimal.toDecimal(hexA);
int decB = Hexadecimal.toDecimal(hexB);
System.out.println("Hex A:\t\t\tHex B:");
System.out.println(hexA + "\t\t\t" + hexB);
System.out.println("Decimal A:\t\tDecimal B:");
System.out.println(decA + "\t\t" + decB);
res = Hexadecimal.subtraction(hexA, hexB);
System.out.println("Substract:\t\tDecimal");
System.out.println(res + "\t\t\t" + Hexadecimal.toDecimal(res));
System.out.println("\nOctal");
String octA = Octal.toOctal(a);
String octB = Octal.toOctal(b);
int deA = Octal.toDecimal(octA);
int deB = Octal.toDecimal(octB);
System.out.println("Oct A:\t\t\tOct B:");
System.out.println(octA + "\t\t" + octB);
System.out.println("Decimal A:\t\tDecimal B:");
System.out.println(deA + "\t\t" + deB);
res = Octal.subtraction(octA, octB);
System.out.println("Substract:\t\tDecimal");
System.out.println(res + "\t\t" + Octal.toDecimal(res));
System.out.println("\nFloat to binary: " + Binary.toBinary((num)));
System.out.println();
}
}
package converter;
/**
* Class utility for converting numbers to octal and back
* Addition and subtraction works, but I'm not sure that It works right always
* Converter works right.
* <b>Functions:</b>
* <ul>
* <li>Converting integer to octal string</li>
* <li>Addition octal string numbers</li>
* <li>Subtraction octal string numbers</li>
* </ul>
*
* @author tkaczenko
*/
public class Octal {
private static String digits = "01234567";
public static String addition(String s1, String s2) {
if (s1 == null || s2 == null) return "";
int first = s1.length() - 1;
int second = s2.length() - 1;
StringBuilder sb = new StringBuilder();
int carry = 0;
while (first >= 0 || second >= 0) {
int sum = carry;
if (first >= 0) {
sum += digits.indexOf(s1.charAt(first));
first--;
}
if (second >= 0) {
sum += digits.indexOf(s2.charAt(second));
second--;
}
carry = sum >> 3;
sum = sum & 0x07;
sb.append(digits.charAt(sum));
}
if (carry > 0)
sb.append(digits.charAt(carry & 0x07));
sb.reverse();
return sb.toString();
}
public static String subtraction(String s1, String s2) {
if (s1 == null || s2 == null) return "";
int first = s1.length() - 1;
int second = s2.length() - 1;
StringBuilder sb = new StringBuilder();
int carry = 0;
while (first >= 0 || second >= 0) {
int sub = carry;
if (first >= 0) {
sub += digits.indexOf(s1.charAt(first));
first--;
}
if (second >= 0) {
sub -= digits.indexOf(s2.charAt(second));
second--;
}
carry = sub >> 3;
sub = sub & 0x07;
sb.append(digits.charAt(sub));
}
if (carry > 0)
sb.append(digits.charAt(carry & 0x07));
sb.reverse();
return sb.toString();
}
public static String toOctal(int num) {
StringBuilder stringBuilder = new StringBuilder();
while (num > 0) {
int j = num & 0x07;
stringBuilder.insert(0, digits.charAt(j));
num >>= 3;
}
return stringBuilder.toString();
}
public static int toDecimal(String str) {
double val = 0;
for (int i = 0; i < str.length(); i++) {
val += Math.pow(8, str.length() - 1 - i) * digits.indexOf(str.charAt(i));
}
return (int) val;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment