(Java) Specify number of bits (length) when converting binary number to string? - java

I'm trying to store a number as a binary string in an array but I need to specify how many bits to store it as.
For example, if I need to store 0 with two bits I need a string "00". Or 1010 with 6 bits so "001010".
Can anyone help?
EDIT: Thanks guys, as I'm rubbish at maths/programming in general I've gone with the simplest solution which was David's. Something like:
binaryString.append(Integer.toBinaryString(binaryNumber));
for(int n=binaryString.length(); n<numberOfBits; n++) {
binaryString.insert(0, "0");
}
It seems to work fine, so unless it's very inefficient I'll go with it.

Use Integer.toBinaryString() then check the string length and prepend it with as many zeros as you need to make your desired length.

Forget about home-made solutions. Use standard BigInteger instead. You can specify number of bits and then use toString(int radix) method to recover what you need (I assume you need radix=2).
EDIT: I would leave bit control to BigInteger. The object will internally resize its bit buffer to fit the new number dimension. Moreover arithmetic operations can be carried out by means of this object (you do not have to implement binary adders/multipliers etc.). Here is a basic example:
package test;
import java.math.BigInteger;
public class TestBigInteger
{
public static void main(String[] args)
{
String value = "1010";
BigInteger bi = new BigInteger(value,2);
// Arithmetic operations
System.out.println("Output: " + bi.toString(2));
bi = bi.add(bi); // 10 + 10
System.out.println("Output: " + bi.toString(2));
bi = bi.multiply(bi); // 20 * 20
System.out.println("Output: " + bi.toString(2));
/*
* Padded to the next event number of bits
*/
System.out.println("Padded Output: " + pad(bi.toString(2), bi.bitLength() + bi.bitLength() % 2));
}
static String pad(String s, int numDigits)
{
StringBuffer sb = new StringBuffer(s);
int numZeros = numDigits - s.length();
while(numZeros-- > 0) {
sb.insert(0, "0");
}
return sb.toString();
}
}

This is a common homework problem. There's a cool loop that you can write that will compute the smallest power of 2 >= your target number n.
Since it's a power of 2, the base 2 logarithm is the number of bits. But the Java math library only offers natural logarithm.
math.log( n ) / math.log(2.0)
is the number of bits.

Even simpler:
String binAddr = Integer.toBinaryString(Integer.parseInt(hexAddr, 16));
String.format("%032", new BigInteger(binAddr));
The idea here is to parse the string back in as a decimal number temporarily (one that just so happens to consist of all 1's and 0's) and then use String.format().
Note that you basically have to use BigInteger, because binary strings quickly overflow Integer and Long resulting in NumberFormatExceptions if you try to use Integer.fromString() or Long.fromString().

Try this:
String binaryString = String.format("%"+Integer.toString(size)+"s",Integer.toBinaryString(19)).replace(" ","0");
where size can be any number the user wants

Here's a simple solution for int values; it should be obvious how to extend it to e.g. byte, etc.
public static String bitString(int i, int len) {
len = Math.min(32, Math.max(len, 1));
char[] cs = new char[len];
for (int j = len - 1, b = 1; 0 <= j; --j, b <<= 1) {
cs[j] = ((i & b) == 0) ? '0' : '1';
}
return new String(cs);
}
Here is the output from a set of sample test cases:
0 1 0 0
0 -1 0 0
0 40 00000000000000000000000000000000 00000000000000000000000000000000
13 1 1 1
13 2 01 01
13 3 101 101
13 4 1101 1101
13 5 01101 01101
-13 1 1 1
-13 2 11 11
-13 3 011 011
-13 4 0011 0011
-13 5 10011 10011
-13 -1 1 1
-13 40 11111111111111111111111111110011 11111111111111111111111111110011
Of course, you're on your own to make the length parameter adequate to represent the entire value.

import java.util.BitSet;
public class StringifyByte {
public static void main(String[] args) {
byte myByte = (byte) 0x00;
int length = 2;
System.out.println("myByte: 0x" + String.valueOf(myByte));
System.out.println("bitString: " + stringifyByte(myByte, length));
myByte = (byte) 0x0a;
length = 6;
System.out.println("myByte: 0x" + String.valueOf(myByte));
System.out.println("bitString: " + stringifyByte(myByte, length));
}
public static String stringifyByte(byte b, int len) {
StringBuffer bitStr = new StringBuffer(len);
BitSet bits = new BitSet(len);
for (int i = 0; i < len; i++)
{
bits.set (i, (b & 1) == 1);
if (bits.get(i)) bitStr.append("1"); else bitStr.append("0");
b >>= 1;
}
return reverseIt(bitStr.toString());
}
public static String reverseIt(String source) {
int i, len = source.length();
StringBuffer dest = new StringBuffer(len);
for (i = (len - 1); i >= 0; i--)
dest.append(source.charAt(i));
return dest.toString();
}
}
Output:
myByte: 0x0
bitString: 00
myByte: 0x10
bitString: 001010

So here instead of 8 you can write your desired length and it will append zeros accordingly. If the length of your mentioned integer exceeds that of the number mentioned then it will not append any zeros
String.format("%08d",1111);
Output:00001111
String.format("%02d",1111);
output:1111

Related

How to convert a binary String to a decimal string in Java

I was working on a homework and thought I had finished but the teacher told me that it wasn't what he was looking for so I need to know how I can convert a binary number that is stored as a String to a decimal string without using any built-in function outside of length(), charAt(), power function, and floor/ceiling in Java.
This is what I had on the beginning.
import java.util.Scanner;
public class inclass2Fall15Second {
public static void convertBinaryToDecimalString() {
Scanner myscnr = new Scanner(System.in);
int decimal = 0;
String binary;
System.out.println("Please enter a binary number: ");
binary = myscnr.nextLine();
decimal = Integer.parseInt(binary, 2);
System.out.println("The decimal number that corresponds to " + binary + " is " + decimal);
}
public static void main (String[] args) {
convertBinaryToDecimalString();
}
}
To convert a base 2 (binary) representation to base 10 (decimal), multiply the value of each bit with 2^(bit position) and sum the values.
e.g. 1011 -> (1 * 2^0) + (1 * 2^1) + (0 * 2^2) + (1 * 2^3) = 1 + 2 + 0 + 8 = 11
Since binary is read from right-to-left (i.e. LSB (least significant bit) is on the rightmost bit and MSB (most-significant-bit) is the leftmost bit), we traverse the string in reverse order.
To get the bit value, subtract '0' from the char. This will subtract the ascii value of the character with the ascii value of '0', giving you the integer value of the bit.
To calculate 2^(bit position), we can keep a count of the bit position, and increment the count on each iteration. Then we can just do 1 << count to obtain the value for 2 ^ (bit position). Alternatively, you could do Math.pow(2, count) as well, but the former is more efficient, since its just a shift-left instruction.
Here's the code that implements the above:
public static int convertBinStrToInt(String binStr) {
int dec = 0, count = 0;
for (int i = binStr.length()-1; i >=0; i--) {
dec += (binStr.charAt(i) - '0') * (1 << count++);
}
return dec;
}

How to decode a 9 digit integer to some random 4 digit word

How to encode a 7 digit integer to a 4 digit string In java?
I have a base36 decoder, which is generating 6 characters,
ex:230150206 is converted to 3T0X1A.
The code for it is as follows:
String f = "230150206";
int d = Integer.parseInt(f.toString());
StringBuffer b36num = new StringBuffer();
do {
b36num.insert(0,(base36(d%36)));
d = d/ 36;
} while (d > 36);
b36num.insert(0,(base36(d)));
System.out.println(b36num.toString());
}
/**
Take a number between 0 and 35 and return the character reprsenting
the number. 0 is 0, 1 is 1, 10 is A, 11 is B... 35 is Z
#param int the number to change to base36
#return Character resprenting number in base36
*/
private static Character base36 (int x) {
if (x == 10)
x = 48;
else if (x < 10)
x = x + 48;
else
x = x + 54;
return new Character((char)x);
}
Can some one share me some other way to achieve this?.
The obtained string can be made in to a substring, but i am looking any other way to do it.
Here is a method, in a simple test program. This method allows any String to represent the digits for the result. As the initial print shows, 62 digits should be sufficient to cover all 7 decimal digit numbers with no more than a 4 character output, so I recommend the decimal digits, lower case alpha and upper case alpha for the 7 digit case.
To cover 9 decimal digits in four encoded digits you would need at least 178 characters, which is not possible using only the 7-bit ASCII characters. You would have to decide which additional characters to use as digits.
public class Test {
public static void main(String[] args) {
String characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(Math.pow(characters.length(), 4));
testit(230150206, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
testit(230150206, characters);
}
private static void testit(int num, String characters){
System.out.println(num + " "+compact(num, characters));
}
public static String compact(int num, String characters){
StringBuffer compacted = new StringBuffer();
while(num != 0){
compacted.insert(0, characters.charAt(num % characters.length()));
num /= characters.length();
}
return compacted.toString();
}
}
Output:
1.4776336E7
230150206 3T0X1A
230150206 fzGA6
All 7 digit numbers in base 10 can fit inside 24 bits (log2(9999999) < 24), that is 3 bytes. Ascii85 requires 20% of extra space to encode which will make it fit in 4 bytes.
Based on this answer by Mat Banik, you can do this:
public class Ascii85Test {
static int[] numbers = {
9999999,
490,
7910940,
};
public static void main(String[] args) {
for(int number : numbers) {
// Convert the number into 3 bytes
byte[] numberBytes = new byte[3];
numberBytes[0] = (byte) ((number >> 16) & 0xFF);
numberBytes[1] = (byte) ((number >> 8) & 0xFF);
numberBytes[2] = (byte) (number & 0xFF);
// Ascii85 encode the bytes
String encoded = Ascii85Coder.encodeBytesToAscii85(numberBytes);
// The encoded string will be "<4 characters>~\n", so we only need to keep the first 4 characters
encoded = Ascii85Coder.encodeBytesToAscii85(numberBytes).substring(0, 4);
// Decode them again, add the trailing ~ that we trimmed
byte[] decodedBytes = Ascii85Coder.decodeAscii85StringToBytes(encoded + "~");
// Convert the 3 bytes into a number
int decodedNumber = ((decodedBytes[0] << 16) & 0xFF0000)
| ((decodedBytes[1] << 8) & 0xFF00)
| (decodedBytes[2] & 0xFF);
System.out.printf("%s -> %s -> %s%n", number, encoded, decodedNumber);
}
}
}
Output:
9999999 -> R$N4 -> 9999999
490 -> !!2? -> 490
7910940 -> Gd\R -> 7910940
An int in Java can have a maximum of 10 digits (11 if you count the minus sign) and take up 4 bytes. With the 20% overhead of Ascii85 this means that we can encode any integer using 5 characters.

counting number of ones in binary representation of a number [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Best algorithm to count the number of set bits in a 32-bit integer?
I want to find out how many 1s are there in binary representation of a number.I have 2 logic .
int count =0;
int no = 4;
while(no!=0){
int d = no%2;
if(d==1)
count++;
no = no/2;
str = str+ d;
}
Now second logic is to keep on masking number iteratively with 1,2,4,8,32 and check if result is 1,2,4, 8..... Am not geting what should be ending condition for this loop.
Use Java API(java 5 or above).
Integer.bitCount(int);
Long.bitCount(long);
NOTE: The above java methods are based on hacker's delight
faster than any of the earlier answers:
(proportional to number of 1 bits rather than total bits)
public class Foo {
public static void main(String[] argv) throws Exception {
int no = 12345;
int count;
for (count = 0; no > 0; ++count) {
no &= no - 1;
}
System.out.println(count);
}
}
Looks like c/c++/c#, if so you have shifting.. just loop to N-1 bits from 0 and use sum+=(value>>i)&1
Ie: you always check the last/right most bit but move the binary representation of the number to the right for every iteration until you have no more bits to check.
Also, think about signed/unsigned and any integer format. But you dont state how that should be handled in the question.
We can make use of overflow for your loop:
int count = 0;
int number = 37;
int mask = 1;
while(mask!=0)
{
int d = number & mask;
if(d != 0)
count++;
/* Double mask until we overflow, which will result in mask = 0... */
mask = mask << 1;
str = str+ d;
}
One idea that's commonly employed for counting ones is to build a lookup table containing the answers for each individual byte, then to split apart your number into four bytes and sum the totals up. This requires four lookups and is quite fast. You can build this table by writing a program that manually computes the answer (perhaps using your above program), and then can write a function like this:
private static final int[] BYTE_TOTALS = /* ... generate this ... */;
public static int countOneBits(int value) {
return BYTE_TOTALS[value & 0xFF] +
BYTE_TOTALS[value >>> 8 & 0xFF] +
BYTE_TOTALS[value >>> 16 & 0xFF] +
BYTE_TOTALS[value >>> 24 & 0xFF];
}
Hope this helps!
There are various ways to do this very fast.
MIT HAKMEM Count
int no =1234;
int tmp =0;
tmp = no - ((no >> 1) & 033333333333) - ((no >> 2) & 011111111111);
System.out.println( ((tmp + (tmp >> 3)) & 030707070707) % 63);
Your end condition should be keeping track of the magnitude of the bit you are at; if it is larger than the original number you are done (will get only 0s from now on).
Oh, and since you didn't specify a language, here's a Ruby solution :)
class Integer
def count_binary_ones
to_s(2).scan('1').length
end
end
42.count_binary_ones #=> 3
How about using the BigInteger class.
public void function(int checkedNumber) {
BigInteger val = new BigInteger(String.valueOf(checkedNumber));
val = val.abs();
int count = val.bitCount();
String binaryString = val.toString(2);
System.out.println("count = " + count);
System.out.println("bin = " + binaryString);
}
The result of function(42); is following.
count = 3
bin = 101010

Sum of the bits in Java

sorry Friends i did a mistake. I have did this mistake again. am really very sorry.
this is the Issue.
I have a time range like
int Starttime = 2 which mean(02:00)
int enttime = 8 which mean(08:00)
i want time in sum of bits,
example
00:00 1
01:00 2
02:00 4 -----
03:00 8 R
04:00 16 a
05:00 32 n
06:00 64 g
07:00 128 e
08:00 256 -----
and soo on till 23:00
so i need totalRange = 256+128+64+32+16+8+4 ;
it should be like this
sorry again.
Thanks
The table indicates that you want to map the hour value of a time to an integer value using this function:
int value = (int) Math.pow(2, hourValue);
or, in other words, 00:00h will map to 20, 12:00h to 212 and so on.
Now if you have need the sum of start and endtime, you can simple use the function from above and add the values:
int totalrange = (int) Math.pow(2, starttime) + (int) Math.pow(2, endtime);
Now if you have starttime=2 and endtime=23, this will give a result (written in binary):
01000000 00000000 00000100
shamelessly adapting polygenelubricants much faster solution:
int totalrange = (1 << starttime) + (1 << endtime);
This works, because 2i is equal to (1 << i).
System.out.println(Integer.toBinaryString(2+24)); // 11010
This uses the Integer.toBinaryString method. There's also toHexString, toOctalString, and a toString with variable radix.
If you need the string to be zero-padded to a specific width, you can write something simple like this:
static String binaryPadded(int n, int width) {
String s = Integer.toBinaryString(n);
return "00000000000000000000000000000000"
.substring(0, width - s.length()) + s;
}
//...
System.out.println(binaryPadded(2+24, 8)); // 00011010
There are different ways to zero pad a string to a fixed width, but this will work for any int value.
For hexadecimal or octal, you can use formatting string instead:
System.out.println(String.format("%04X", 255)); // 00FF
The specification isn't very clear, but it looks like you want this mapping:
0 -> 1
1 -> 2
2 -> 4
3 -> 8
4 -> 16
:
i -> 2i
In that case, your mapping is from i to (1 << i) (the << is the bitwise left-shift operator).
System.out.println(
(1 << 2) + (1 << 4)
); // 20
Note that depending on what is it that you're trying to do, you may also consider using a java.util.BitSet instead.
BitSet demonstration
This may be completely off-the-mark, but assuming that you're doing some sort of interval arithmetics, then BitSet may be the data structure for you (see also on ideone.com):
import java.util.BitSet;
//...
static String interval(BitSet bs) {
int i = bs.nextSetBit(0);
int j = bs.nextClearBit(i);
return String.format("%02d:00-%02d:00", i, j);
}
public static void main(String[] args) {
BitSet workTime = new BitSet();
workTime.set(9, 17);
System.out.println(interval(workTime));
// 09:00-17:00
BitSet stackOverflowTime = new BitSet();
stackOverflowTime.set(10, 20);
System.out.println(interval(stackOverflowTime));
// 10:00-20:00
BitSet busyTime = new BitSet();
busyTime.or(workTime);
busyTime.or(stackOverflowTime);
System.out.println(interval(busyTime));
// 09:00-20:00
}
Note that methods like nextSetBit and nextClearBit makes it easy to find empty/occupied time slots. You can also do intersect, or, and, etc.
This simple example only finds the first interval, but you can make this more sophisticated and do various arithmetics on non-contiguous time intervals.
Integer.toBinaryString(i)
Returns a string representation of the integer argument as anunsigned integer in base 2.
To compute the length of the time-interval, you have to do
int totalrange = endtime - starttime;
Perhaps this is what you're looking for:
int startTime = 2;
int endTime = 24;
int range = endTime - startTime;
System.out.println(range + " can be expressed as the following sum:");
for (int size = 1; range > 0; size <<= 1, range >>= 1)
if ((range & 1) != 0)
System.out.format("+ %02d:00%n", size);
Output:
22 can be expressed as the following sum:
+ 02:00
+ 04:00
+ 16:00

Algorithm for binary arithmetic in Java

On paper, binary arithmetic is simple, but as a beginning programmer, I'm finding it a little difficult to come up with algorithms for the addition, subtraction, multiplication and division of binary numbers.
I have two binary numbers stored as strings, assume that any leading zeroes have been dropped. How would I go about performing these operations on the two numbers?
Edit: I need to avoid converting them to an int or long.
Binary string to int:
int i = Integer.parseInt("10101011", 2);
int j = Integer.parseInt("00010", 2);
Then you can do anything you please with the two ints, eg:
i = i + j;
i = i - j;
And to get them back to a binary string:
String s = Integer.toBinaryString(i);
The algorithms, from wikipedia:
Addition:
The simplest arithmetic operation in
binary is addition. Adding two
single-digit binary numbers is
relatively simple, using a form of
carrying:
0 + 0 → 0
0 + 1 → 1
1 + 0 → 1
1 + 1 → 0, carry 1 (since 1 + 1 = 0 + 1 × 10 in binary)
Adding two "1" digits produces a digit
"0", while 1 will have to be added to
the next column.
Subtraction:
Subtraction works in much the same
way:
0 − 0 → 0
0 − 1 → 1, borrow 1
1 − 0 → 1
1 − 1 → 0
Subtracting a "1" digit from a "0"
digit produces the digit "1", while 1
will have to be subtracted from the
next column. This is known as
borrowing. The principle is the same
as for carrying. When the result of a
subtraction is less than 0, the least
possible value of a digit, the
procedure is to "borrow" the deficit
divided by the radix (that is, 10/10)
from the left, subtracting it from the
next positional value.
Multiplication:
Multiplication in binary is similar to
its decimal counterpart. Two numbers A
and B can be multiplied by partial
products: for each digit in B, the
product of that digit in A is
calculated and written on a new line,
shifted leftward so that its rightmost
digit lines up with the digit in B
that was used. The sum of all these
partial products gives the final
result.
Since there are only two digits in
binary, there are only two possible
outcomes of each partial
multiplication:
* If the digit in B is 0, the partial product is also 0
* If the digit in B is 1, the partial product is equal to A
For example, the binary numbers 1011
and 1010 are multiplied as follows:
1 0 1 1 (A)
× 1 0 1 0 (B)
---------
0 0 0 0 ← Corresponds to a zero in B
+ 1 0 1 1 ← Corresponds to a one in B
+ 0 0 0 0
+ 1 0 1 1
---------------
= 1 1 0 1 1 1 0
The following code implements binary addition without actually doing any arithmetic, binary or otherwise. The actual "addition" is done by lookupTable, and everything else is straight-up string manipulation. I wrote it with the intention of making it as instructive as possible, emphasizing the process instead of efficiency. Hope it helps.
public class BinaryArithmetic {
static String[] lookupTable = {
"0+0+0=00",
"0+0+1=01",
"0+1+0=01",
"0+1+1=10",
"1+0+0=01",
"1+0+1=10",
"1+1+0=10",
"1+1+1=11",
};
static String lookup(char b1, char b2, char c) {
String formula = String.format("%c+%c+%c=", b1, b2, c);
for (String s : lookupTable) {
if (s.startsWith(formula)) {
return s.substring(s.indexOf("=") + 1);
}
}
throw new IllegalArgumentException();
}
static String zeroPad(String s, int length) {
while (s.length() < length) {
s = "0" + s;
}
return s;
}
static String add(String s1, String s2) {
int length = Math.max(s1.length(), s2.length());
s1 = zeroPad(s1, length);
s2 = zeroPad(s2, length);
String result = "";
char carry = '0';
for (int i = length - 1; i >= 0; i--) {
String columnResult = lookup(s1.charAt(i), s2.charAt(i), carry);
result = columnResult.charAt(1) + result;
carry = columnResult.charAt(0);
}
if (carry == '1') {
result = carry + result;
}
return result;
}
public static void main(String args[]) {
System.out.println(add("11101", "1001"));
}
}
While we're at it, I might as well do multiply too.
static String multiply(String s1, String s2) {
String result = "";
String zeroSuffix = "";
for (int i = s2.length() - 1; i >= 0; i--) {
if (s2.charAt(i) == '1') {
result = add(result, s1 + zeroSuffix);
}
zeroSuffix += "0";
}
return result;
}
Working with binary arithmetic is really no different than the more familiar base 10. Let's take addition for example
(1) (1)
182 182 182 182 182
845 845 845 845 845
--- + --- + --- + --- + --- +
7 27 027 1027
So what did you do? You right-align the numbers to add, and you proceed right-to-left, adding one digit at a time, carrying over +1 to the left as necessary.
In binary, the process is exactly the same. In fact, it's even simpler because you only have 2 "digits" now, 0 and 1!
(1) (1) (1)
11101 11101 11101 11101 11101 11101 11101
1001 1001 1001 1001 1001 1001 1001
----- + ----- + ----- + ----- + ----- + ----- + ----- +
0 10 110 0110 00110 100110
The rest of the operations work similarly too: the same process that you use for base 10, works for base 2. And again, it's actually simpler because there are only 2 "digits", 0 and 1. This simplicity is why hardware likes the binary system.
Convert the binary strings to Integers and then operate on the Integers, e.g.
String add(String s1, String s2) {
int i1 = Integer.parseInt(s1);
int i2 = Integer.parseInt(s2);
return Integer.toBinaryString(i1 + i2);
}
The built-in BitSet class is very straight-forward to use for bit-level operations.

Categories

Resources