Help with converting Hex to booleans? - java

I am new at Java. I am learning.
I am trying to do the following:
convert a hexadecimal string into a binary, then process the binary into a series of booleans.
public static void getStatus() {
/*
* CHECKTOKEN is a 4 bit hexadecimal
* String Value in FF format.
* It needs to go into binary format
*/
//LINETOKEN.nextToken = 55 so CHECKTOKEN = 55
CHECKTOKEN = LINETOKEN.nextToken();
//convert to Integer (lose any leading 0s)
int binaryToken = Integer.parseInt(CHECKTOKEN,16);
//convert to binary string so 55 becomes 85 becomes 1010101
//should be 01010101
String binaryValue = Integer.toBinaryString(binaryToken);
//Calculate the number of required leading 0's
int leading0s = 8 - binaryValue.length();
//add leading 0s as needed
while (leading0s != 0) {
binaryValue = "0" + binaryValue;
leading0s = leading0s - 1;
}
//so now I have a properly formatted hex to binary
//binaryValue = 01010101
System.out.println("Indicator" + binaryValue);
/*
* how to get the value of the least
* signigicant digit into a boolean
* variable... and the next?
*/
}
I think there must be a better way to perform the action. This is not elegant. Also, I'm stuck with a binary string value which needs to be processed somehow.

public static void main(String[] args) {
String hexString = "55";
int value = Integer.parseInt(hexString, 16);
int numOfBits = 8;
boolean[] booleans = new boolean[numOfBits];
for (int i = 0; i < numOfBits; i++) {
booleans[i] = (value & 1 << i) != 0;
}
System.out.println(Arrays.toString(booleans));
}

Related

How can I convert this large number hex value to decimal

I am trying to convert string ABCDEF1234567890 to decimal value:
long result = 0;
String hex = "0123456789ABCDEF";
decimal = decimal.toUpperCase();
for(int i = 0; i < decimal.length(); i++) {
char c = decimal.charAt(i);
result += hex.indexOf(c) * Math.pow(16, decimal.length() - 1 - i);
}
return Long.toString(result);
I know the class BigInteger but i don't know how to use it in my code. please help me
The BigInteger class has a constructor which accepts a string and radix:
final BigInteger bigInt = new BigInteger(hex, 16);
Note that your specific hex value 0123456789ABCDEF fits into a variable of type long (Long.MAX_VALUE == 0x7fffffffffffffffL) and Long#parseLong accepts a string and radix as well:
final long value = Long.parseLong(hex);

Find the smallest binary number without continous 1

So here is the thing.
I have to write code to show a binary number X's next smallest "code-X number" which is bigger than binary number X.
code-X number is a binary number which have no continuously 1. For example: 1100 is not a code X number because it has 11, and 1001001001 is a code-X number
Here is my code
String a = "11001110101010";
String b = "";
int d = 0;
for(int i = a.length()-1; i>0;i--){
if(a.charAt(i) == '1' && a.charAt(i-1)=='1'){
while(a.charAt(i)=='1'){
b = b + '0';
if(i!=0){i--;}
d++;
}
}
b = b + a.charAt(i);
}
StringBuffer c = new StringBuffer(b);
System.out.println(c.reverse());
I plan on copy the binary string to string b, replace every '1' which next i is '1' into '0' and insert an '1'
like:
1100 ---> 10000
but i have no idea how to do it :)
May you help me some how? Thanks
Try this. This handles arbitrary length bit strings. The algorithm is as follows.
Needed to conditionally modify last two bits to force a change if the number is not a codeEx number. This ensures it will be higher. Thanks to John Mitchell for this observation.
Starting from the left, find the first group of 1's. e.g 0110
If not at the beginning replace it with 100 to get 1000
Otherwise, insert 1 at the beginning.
In all cases, replace everything to the right of the grouping with 0's.
String x = "10000101000000000001000001000000001111000000000000110000000000011011";
System.out.println(x.length());
String result = codeX(x);
System.out.println(x);
System.out.println(result);
public static String codeX(String bitStr) {
StringBuilder sb = new StringBuilder(bitStr);
int i = 0;
int len = sb.length();
// Make adjust to ensure new number is larger than
// original. If the word ends in 00 or 10, then adding one will
// increase the value in all cases. If it ends in 01
// then replacing with 10 will do the same. Once done
// the algorithm takes over to find the next CodeX number.
if (s.equals("01")) {
sb.replace(len - 2, len, "10");
} else {
sb.replace(len- 1, len, "1");
}
while ((i = sb.indexOf("11")) >= 0) {
sb.replace(i, len, "0".repeat(len - i));
if (i != 0) {
sb.replace(i - 1, i + 2, "100");
} else {
sb.insert(i, "1");
}
}
String str = sb.toString();
i = str.indexOf("1");
return i >= 0 ? str.substring(i) : str;
}
Prints
10000101000000000001000001000000001111000000000000110000000000011011
10000101000000000001000001000000010000000000000000000000000000000000
Using raw binary you can use the following.
public static void main(String[] args) {
long l = 0b1000010100000000010000010000000011110000000000110000000000011011L;
System.out.println(
Long.toBinaryString(nextX(l)));
}
public static long nextX(long l) {
long l2 = l >>> 1;
long next = Long.highestOneBit(l & l2);
long cutoff = next << 1;
long mask = ~(cutoff - 1);
return (l & mask) | cutoff;
}
prints
1000010100000000010000010000000010000000000000000000000000000000
EDIT: Based on #WJS correct way to find the smallest value just larger.
This is a slight expansion WJS' 99% correct answer.
There is just one thing missing, the number is not incremented if there are no consecutive 1's in the original X string.
This modification to the main method handles that.
Edit; Added an else {}. Starting from the end of the string, all digits should be inverted until a 0 is found. Then we change it to a 1 and break before passing the resulting string to WJS' codeX function.
(codeX version does not include sb.replace(len-2,len,"11");)
public static void main(String[] args) {
String x = "10100";
StringBuilder sb = new StringBuilder(x);
if (!x.contains("11")) {
for (int i = sb.length()-1; i >= 0; i--) {
if (sb.charAt(i) == '0') {
sb.setCharAt(i, '1');
break;
} else {
sb.setCharAt(i, '0');
}
}
}
String result = codeX(sb.toString());
System.out.println(x);
System.out.println(result);
}

How to convert a long into printable bytes

I have a string which represent a long. Like "12345678901" (11 chars long).
I convert it into a long using Long.parse(), that's fine.
Now, I want to send this long as a short string, like "eR%s" over the wire.
The goal is to have this final string as short as possible. Any idea what's the best way to do that? I can use more characters as the URL encoding (Like I can use /, %, :, etc.)
Java can handle a radix as high as 36 using the digits 0 - 9 and lower case letters a - z.
> Long.toString(12345678901L, 36)
"5o6aqt1"
> Long.parseLong("5o6aqt1", 36)
12345678901
You could create your own encoding using 65 of the 66 unreserved URI Characters (so your URI would not need escaping). The '-' sign needs to be used for negative numbers:
> Long65.toString(12345678901L)
"aFDIbA"
> Long65.parseLong65("aFDIbA")
12345678901
Here is the code for Long65()
import java.math.BigInteger;
public class Long65 {
private static int base = 65;
private static String URIchars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_.~";
public static String toString(Long aNumber) {
StringBuilder result = new StringBuilder();
if (aNumber < 0) {
result.append('-');
aNumber = -aNumber;
}
int r = (int)(aNumber % base);
if (aNumber - r == 0)
result.append(URIchars.charAt(r));
else
result.append(Long65.toString((aNumber - r) / base) + URIchars.charAt(r));
return result.toString();
}
public static long parseLong65(String aNumber) {
char[] digits;
int sign = 1;
if (aNumber.charAt(0) == '-') {
sign = -1;
digits = aNumber.substring(1).toCharArray();
} else {
digits = aNumber.toCharArray();
}
BigInteger bigBase = BigInteger.valueOf(base);
BigInteger power = bigBase.pow(digits.length);
BigInteger total = BigInteger.valueOf(0);
for (char digit : digits){
power = power.divide(bigBase);
total = total.add(power.multiply(BigInteger.valueOf(URIchars.indexOf(digit))));
}
return sign * total.longValue();
}
}
Use a different base for your number if you want a shorter representation.
The bigger the numeric base you use, the smaller the representation. You can try base 16 for example:
Long.toString(num, 16)
This should return a string of at most 16 characters.
If that's not small enough, you can build a representation in a bigger base. However, if the resulting string needs to be URL escaped, this may not be useful. In base 256 for example, 8 chars would be enough for any number, but many of the 256 chars need to be escaped, making the resulting text longer. So you have to choose your alphabet carefully, if you choose to implement such an encoding/decoding scheme yourself.
Take a look at http://en.wikipedia.org/wiki/Base64 for example. You can use this Java implementation. You may also be interested in Base85 and its implementations.
To reply to the comments Base64 vs other options, I will say, it all depends on the constraints you have on the character set. I'm not talking about transmitting over an URL, but over a char stream which need to be a text stream. I can not simply send a byte array since non-printable chars might cause certain issues.
So I built something like that (see below) which transforms a long in base92 (almost). It uses all the printable chars excluding minus and pipe which I use for delimiters.
It's almost a cut&past of Base65 where I simply build the list of valid digits dynamically. Can be reuse for any base or any list of valid digits.
<!-- language: java -->
public class LongConverter {
private static String URIchars;
static {
StringBuilder result = new StringBuilder();
for (int i = 32; i < 255; i++) {
if ((i != 45) && (i != 124))
result.append((char)i);
}
URIchars = result.toString();
}
public static String toString(Long aNumber) {
int base = URIchars.length();
StringBuilder result = new StringBuilder();
if (aNumber < 0) {
result.append('-');
aNumber = -aNumber;
}
int r = (int) (aNumber % base);
if (aNumber - r == 0) result.append(URIchars.charAt(r));
else result.append(Long65.toString((aNumber - r) / base) + URIchars.charAt(r));
return result.toString();
}
public static long parseLong(String aNumber) {
int base = URIchars.length();
char[] digits;
int sign = 1;
if (aNumber.charAt(0) == '-') {
sign = -1;
digits = aNumber.substring(1).toCharArray();
} else {
digits = aNumber.toCharArray();
}
long total = 0;
long power = 1;
for (int i = 0; i < digits.length; i++)
power *= base;
for (char digit : digits) {
power /= base;
total += URIchars.indexOf(digit) * power;
}
return sign * total;
}
}

Java converting negative binary back to integer

I'm trying to convert an base 10 number to a base 2 and back to base 10. It works only for positive argument_decimal
argument_binary = Integer.toBinaryString(argument_decimal);
back_converted_argument_decimal = Integer.valueOf(argument_binary, 2);
For argument_decimal beeing negative, I get "java.lang.NumberFormatException: For input string: "11111111111111111111111111111111""
EDIT: here is what I do:
latitude_binary = Integer.toBinaryString((int)(latitude_decimal * 1000000));
back_converted_latitude_decimal = Long.parseLong(latitude_binary, 2) / 1000000.0;
which gives me bad results like -1.1 being forth and back converted to 4293.867296
Try to go via a long:
String binary = Integer.toBinaryString(-1);
long l = Long.parseLong(binary, 2);
int i = (int) l;
Tested, and working.
Why this works is because -1 is represented as a sequence of 32 bits 1 in system memory. When using the toBinaryString method, it creates a string using that exact representation. But, 32 bits of one is in fact equal to 2^32 - 1. That is too large for an int (4 bytes), because an int goes from [-2^31, 2^31-1]. This is because the most left bit is representing the sign. So to fix that overflow, first interpret that sequence of 1 and 0 characters as a Long. A long will do because the maximum value for a long is 2^63-1. Then convert the long to an int. This is done by simply taking the lower 32 bits.
The bug in your code is that you didn't cast the Long.parseLong to an int. So this should work:
lat_bin = Integer.toBinaryString((int)(lat_dec * 1000000));
lat_dec_conv = ((int) Long.parseLong(lat_bin, 2)) / 1000000.0;
public static void convertStringToDecimal(String binary) {
int decimal = 0;
int power = 0;
if (binary.charAt(0) == '1' && binary.length() == 32) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < binary.length(); i++) {
builder.append((binary.charAt(i) == '1' ? '0' : '1'));
}
while (binary.length() > 0) {
int temp = Integer
.parseInt(builder.charAt((binary.length()) - 1)+"");
decimal += temp * Math.pow(2, power++);
binary = binary.substring(0, binary.length() - 1);
}
System.out.println((decimal + 1) * (-1));
} else {
while (binary.length() > 0) {
int temp = Integer
.parseInt(binary.charAt((binary.length()) - 1) + "");
decimal += temp * Math.pow(2, power++);
binary = binary.substring(0, binary.length() - 1);
}
System.out.println(decimal);
}
}

Print an integer in binary format in Java

I have a number and I want to print it in binary. I don't want to do it by writing an algorithm.
Is there any built-in function for that in Java?
Assuming you mean "built-in":
int x = 100;
System.out.println(Integer.toBinaryString(x));
See Integer documentation.
(Long has a similar method, BigInteger has an instance method where you can specify the radix.)
Here no need to depend only on binary or any other format... one flexible built in function is available That prints whichever format you want in your program.. Integer.toString(int, representation)
Integer.toString(100,8) // prints 144 --octal representation
Integer.toString(100,2) // prints 1100100 --binary representation
Integer.toString(100,16) //prints 64 --Hex representation
System.out.println(Integer.toBinaryString(343));
I needed something to print things out nicely and separate the bits every n-bit. In other words display the leading zeros and show something like this:
n = 5463
output = 0000 0000 0000 0000 0001 0101 0101 0111
So here's what I wrote:
/**
* Converts an integer to a 32-bit binary string
* #param number
* The number to convert
* #param groupSize
* The number of bits in a group
* #return
* The 32-bit long bit string
*/
public static String intToString(int number, int groupSize) {
StringBuilder result = new StringBuilder();
for(int i = 31; i >= 0 ; i--) {
int mask = 1 << i;
result.append((number & mask) != 0 ? "1" : "0");
if (i % groupSize == 0)
result.append(" ");
}
result.replace(result.length() - 1, result.length(), "");
return result.toString();
}
Invoke it like this:
public static void main(String[] args) {
System.out.println(intToString(5463, 4));
}
public static void main(String[] args)
{
int i = 13;
short s = 13;
byte b = 13;
System.out.println("i: " + String.format("%32s",
Integer.toBinaryString(i)).replaceAll(" ", "0"));
System.out.println("s: " + String.format("%16s",
Integer.toBinaryString(0xFFFF & s)).replaceAll(" ", "0"));
System.out.println("b: " + String.format("%8s",
Integer.toBinaryString(0xFF & b)).replaceAll(" ", "0"));
}
Output:
i: 00000000000000000000000000001101
s: 0000000000001101
b: 00001101
Old school:
int value = 28;
for(int i = 1, j = 0; i < 256; i = i << 1, j++)
System.out.println(j + " " + ((value & i) > 0 ? 1 : 0));
Output (least significant bit is on 0 position):
0 0
1 0
2 1
3 1
4 1
5 0
6 0
7 0
check out this logic can convert a number to any base
public static void toBase(int number, int base) {
String binary = "";
int temp = number/2+1;
for (int j = 0; j < temp ; j++) {
try {
binary += "" + number % base;
number /= base;
} catch (Exception e) {
}
}
for (int j = binary.length() - 1; j >= 0; j--) {
System.out.print(binary.charAt(j));
}
}
OR
StringBuilder binary = new StringBuilder();
int n=15;
while (n>0) {
if((n&1)==1){
binary.append(1);
}else
binary.append(0);
n>>=1;
}
System.out.println(binary.reverse());
This is the simplest way of printing the internal binary representation of an integer.
For Example: If we take n as 17 then the output will be: 0000 0000 0000 0000 0000 0000 0001 0001
void bitPattern(int n) {
int mask = 1 << 31;
int count = 0;
while(mask != 0) {
if(count%4 == 0)
System.out.print(" ");
if((mask&n) == 0)
System.out.print("0");
else
System.out.print("1");
count++;
mask = mask >>> 1;
}
System.out.println();
}
Simple and pretty easiest solution.
public static String intToBinaryString(int integer, int numberOfBits) {
if (numberOfBits > 0) { // To prevent FormatFlagsConversionMismatchException.
String nBits = String.format("%" + numberOfBits + "s", // Int to bits conversion
Integer.toBinaryString(integer))
.replaceAll(" ","0");
return nBits; // returning the Bits for the given int.
}
return null; // if the numberOfBits is not greater than 0, returning null.
}
Solution using 32 bit display mask,
public static String toBinaryString(int n){
StringBuilder res=new StringBuilder();
//res= Integer.toBinaryString(n); or
int displayMask=1<<31;
for (int i=1;i<=32;i++){
res.append((n & displayMask)==0?'0':'1');
n=n<<1;
if (i%8==0) res.append(' ');
}
return res.toString();
}
System.out.println(BitUtil.toBinaryString(30));
O/P:
00000000 00000000 00000000 00011110
Simply try it. If the scope is only printing the binary values of the given integer value. It can be positive or negative.
public static void printBinaryNumbers(int n) {
char[] arr = Integer.toBinaryString(n).toCharArray();
StringBuilder sb = new StringBuilder();
for (Character c : arr) {
sb.append(c);
}
System.out.println(sb);
}
input
5
Output
101
There are already good answers posted here for this question. But, this is the way I've tried myself (and might be the easiest logic based → modulo/divide/add):
int decimalOrBinary = 345;
StringBuilder builder = new StringBuilder();
do {
builder.append(decimalOrBinary % 2);
decimalOrBinary = decimalOrBinary / 2;
} while (decimalOrBinary > 0);
System.out.println(builder.reverse().toString()); //prints 101011001
Binary representation of given int x with left padded zeros:
org.apache.commons.lang3.StringUtils.leftPad(Integer.toBinaryString(x), 32, '0')
You can use bit mask (1<< k) and do AND operation with number!
1 << k has one bit at k position!
private void printBits(int x) {
for(int i = 31; i >= 0; i--) {
if((x & (1 << i)) != 0){
System.out.print(1);
}else {
System.out.print(0);
}
}
System.out.println();
}
The question is tricky in java (and probably also in other language).
A Integer is a 32-bit signed data type, but Integer.toBinaryString() returns a string representation of the integer argument as an unsigned integer in base 2.
So, Integer.parseInt(Integer.toBinaryString(X),2) can generate an exception (signed vs. unsigned).
The safe way is to use Integer.toString(X,2); this will generate something less elegant:
-11110100110
But it works!!!
I think it's the simplest algorithm so far (for those who don't want to use built-in functions):
public static String convertNumber(int a) {
StringBuilder sb=new StringBuilder();
sb.append(a & 1);
while ((a>>=1) != 0) {
sb.append(a & 1);
}
sb.append("b0");
return sb.reverse().toString();
}
Example:
convertNumber(1) --> "0b1"
convertNumber(5) --> "0b101"
convertNumber(117) --> "0b1110101"
How it works: while-loop moves a-number to the right (replacing the last bit with second-to-last, etc), gets the last bit's value and puts it in StringBuilder, repeats until there are no bits left (that's when a=0).
for(int i = 1; i <= 256; i++)
{
System.out.print(i + " "); //show integer
System.out.println(Integer.toBinaryString(i) + " "); //show binary
System.out.print(Integer.toOctalString(i) + " "); //show octal
System.out.print(Integer.toHexString(i) + " "); //show hex
}
Try this way:
public class Bin {
public static void main(String[] args) {
System.out.println(toBinary(0x94, 8));
}
public static String toBinary(int a, int bits) {
if (--bits > 0)
return toBinary(a>>1, bits)+((a&0x1)==0?"0":"1");
else
return (a&0x1)==0?"0":"1";
}
}
10010100
Enter any decimal number as an input. After that we operations like modulo and division to convert the given input into binary number.
Here is the source code of the Java Program to Convert Integer Values into Binary and the bits number of this binary for his decimal number.
The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int integer ;
String binary = ""; // here we count "" or null
// just String binary = null;
System.out.print("Enter the binary Number: ");
integer = sc.nextInt();
while(integer>0)
{
int x = integer % 2;
binary = x + binary;
integer = integer / 2;
}
System.out.println("Your binary number is : "+binary);
System.out.println("your binary length : " + binary.length());
}
}
Since no answer is accepted, maybe your question was about how to store an integer in an binary-file.
java.io.DataOutputStream might be what you're looking for: https://docs.oracle.com/javase/8/docs/api/java/io/DataOutputStream.html
DataOutputStream os = new DataOutputStream(outputStream);
os.writeInt(42);
os.flush();
os.close();
Integer.toString(value,numbersystem) --- syntax to be used
and pass value
Integer.toString(100,8) // prints 144 --octal
Integer.toString(100,2) // prints 1100100 --binary
Integer.toString(100,16) //prints 64 --Hex
This is my way to format an output of the Integer.toBinaryString method:
public String toBinaryString(int number, int groupSize) {
String binary = Integer.toBinaryString(number);
StringBuilder result = new StringBuilder(binary);
for (int i = 1; i < binary.length(); i++) {
if (i % groupSize == 0) {
result.insert(binary.length() - i, " ");
}
}
return result.toString();
}
The result for the toBinaryString(0xABFABF, 8) is "10101011 11111010 10111111"
and for the toBinaryString(0xABFABF, 4) is "1010 1011 1111 1010 1011 1111"
It works with signed and unsigned values used powerful bit manipulation and generates the first zeroes on the left.
public static String representDigits(int num) {
int checkBit = 1 << (Integer.SIZE * 8 - 2 ); // avoid the first digit
StringBuffer sb = new StringBuffer();
if (num < 0 ) { // checking the first digit
sb.append("1");
} else {
sb.append("0");
}
while(checkBit != 0) {
if ((num & checkBit) == checkBit){
sb.append("1");
} else {
sb.append("0");
}
checkBit >>= 1;
}
return sb.toString();
}
`
long k=272214023L;
String long =
String.format("%64s",Long.toBinaryString(k)).replace(' ','0');
String long1 = String.format("%64s",Long.toBinaryString(k)).replace(' ','0').replaceAll("(\d{8})","$1 ");
`
print :
0000000000000000000000000000000000000000000
00000000 00000000 00000000 00000000 0000000

Categories