For example, if I have
long binarynumber=10011;
and I want it to do
binarynumber=binarynumber>>1;
But instead of discarding the rightmost number(the number would be 01001 in 5 digits), I want it to be 11001 where the last number moves to the first place in the binary "string". The value of the binary number doesn't really matter, since I am using it as a string to output.
Are you talking about doing something like this
public static String circularShiftBinary(long binaryNumber, int shift)
{
String bin = Long.toString(binaryNumber);
//check that the shift isn't a fully circular shift
if(shift % bin.length() != 0)
while(shift-- > 0)
bin = bin.charAt(bin.length() - 1) + bin.substring(0, bin.length() - 1);
return bin;
}
Example call for variations
public static void main(String[] args) {
long binaryNumber = 10011;
int shift = 0;
while(shift < 6)
System.out.println(circularShiftBinary(binaryNumber, shift++));
}//main method
Output
10011
11001
11100
01110
00111
10011
Related
import java.util.*;
public class Binary {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int number = input.nextInt();
String binary = Integer.toBinaryString(number);
System.out.println(binary);
}
}
I am trying to create a program which converts an integer into binary and groups every four bits. For example, if I input 1, I want to get 0001, but I get 1
Let's throw some Streams, Collectors and RegEx into our solution to complete the learning exercise.
Stream / Collector / RegEx solution:
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;
class Binary
{
public static void main( String[] args )
{
Scanner input = new Scanner( System.in );
int number = input.nextInt();
String binary = Integer.toBinaryString( number );
System.out.println( binary );
// SOLUTION:
int digitsInGroup = 4;
String separator = ".";
while( binary.length() % digitsInGroup > 0 )
binary = "0" + binary;
binary = Arrays.stream( binary.split( String.format( "(?<=\\G.{%d})", digitsInGroup ) ) ).collect( Collectors.joining( separator ) );
System.out.println( binary );
}
}
Output:
> java Binary.java
1
1
0001
> java Binary.java
16
10000
0001.0000
> java Binary.java
31000
111100100011000
0111.1001.0001.1000
Take the number 4 bits at a time, and print the bits.
Use a recursive implementation to get the nibbles printed in the correct order.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
printbin(input.nextInt());
}
static void printbin(int number) {
int lo = number & 15;
int hi = number >>> 4;
if (hi != 0) {
printbin(hi);
System.out.print('.');
}
for (int n=3; n>=0; n--) {
System.out.print((lo >> n) & 1);
}
}
Given 291 (which is 0x123) the output is
0001.0010.0011
You can make your own toBinaryString method. But first you have to understand the << operator, it basically shifts binary numbers to the left by the value you give to it.
example:
int n = 1; // 0001
n = ( n<<(4-1) ); // shift the binary number of 1 to the left 3 times
System.out.println(toBinaryString(n)); // = 1000;
now you might ask what is the usage of this? well you can make your own toBinaryString method with the help of the shift operator to do what you want
but before jumping to the code you have to know how the & operator works:
1000 & 0001 = 0
public static String toBinaryString(int n) {
String binary = ""; //Start with an empty String
// int i in binary = 1000, as long as i > 0, divide by 2
for (int i = (1 << (4 - 1)); i > 0; i /= 2) {
// if binary n & i are NOT 0, add 1 to the String binary, Otherwise add 0
binary += (n & i) != 0 ? "1" : "0";
}
return binary;
}
let's say you put 1 as input:
toBinaryString(1); // 1 = 0001 in binary
the function starts:
i starts at a binary value of 1000 which is equal to int 8
is 8 bigger than 0? yes, divide by 2
8/2 = 4;
4 in binary is 00100, now lets compare it with our input 0001
00100 & 0001 = 0? // YES
add 0 to String binary.
now divide 4 by 2 and repeat the loop. The function will add 3 zeros and 1 at the end. That will be your 0001.
At the end of the loop binary will be your wanted value as a String.
I hope i helped
~Mostafa
Primitive approach:
import java.util.*;
public class Binary {
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
int number = input.nextInt();
String binary = Integer.toBinaryString(number);
System.out.println(binary);
int paddingLength = (4 - binary.length() % 4) % 4;
StringBuilder grouped = new StringBuilder();
for (int i = 0; i < paddingLength; i++) {
grouped.append('0');
}
for (int i = 0; i < binary.length(); i++) {
if (i != 0 && (i + paddingLength) % 4 == 0) {
grouped.append('.');
}
grouped.append(binary.charAt(i));
}
System.out.println(grouped);
}
}
}
$ java Binary.java
1
1
0001
$ java Binary.java
16
10000
0001.0000
$
I have upload this code already but it was having some problems and now I have update my code this program does not provide me exact reverse number when I enter 123 it return me 321 but if I enter 001 or 100 it just return me 1 in both case help me to solve this issue
public class Employee {
void fun(int choice) {
int number = choice;
int remander = 0;
int reverse = 0;
while (number >= 1) {
remander = number % 10;> taking remainder here
reverse = reverse * 10 + remander;
number = number / 10;
}
System.out.println(reverse);
}
public static void main(String args[]) {
Employee ob=new Employee();
int choice;
System.out.println("Enter number you want to return");
Scanner obj=new Scanner(System.in);
choice= obj.nextInt();
ob.fun(choice);
}
}
`
Here's a one-liner you can use to convert int to Stream of String numbers, reverse it and return as a String:
Stream.of(Integer.toString(choice).split("")).reduce((c1,c2)->c2+c1).get();
First point: be careful about adding leading 0s to the number. If the number is an integer literal, the leading 0s will actually cause the integer to be interpreted as octal. In this case, 001 octal does, in fact, equal 1 in decimal too, but only due to luck. If you picked another number, it would not give you the result you're expecting; for example, the following code actually prints 63 (not 77):
public class HelloWorld{
public static void main(String []args){
int x = 0077;
System.out.println(x);
}
}
On the other hand, if you're parsing an integer out of a string or using a scanner, the leading 0s will simply be stripped off. For example, the following prints 77:
System.out.println(Integer.parseInt("0077"));
Unfortunately, in neither case will you get 0077, so the leading 0s won't make any difference when you go to do the reverse operation.
Also, think about what happens for 100:
reverse = reverse * 10 + remander;
Reverse is 0 to start with (and 0 * 10 == 0) and 100 % 10 == 0 because 100 is evenly divisible by 10. Put another way, the statement is equal to:
reverse = 0 * 10 + 0;
which clearly equals 0.
You can't do this using Scanner.nextInt() because there is no way to tell if leading zeroes were included once they are converted to an int. And the octal situation is not relevant since Scanner does not process ints that way. So you use either an all String solution and verify the characters are digits or use a hybrid of both math and String methods. I did the latter. The following:
reads in a String
converts to an int
calculates the number of leading zeroes by using the log10 of the
int and the length of the entered string.
Allocates a StringBuilder to hold the result.
Scanner input = new Scanner(System.in);
String val = input.nextLine();
int numb = Integer.valueOf(val);
int len = val.length();
// exponent of the entered number rounded up to the next int.
// This computes the number of digits in the actual int value.
int exp = (int) Math.log10(numb) + 1;
// now reverse the integer and store in the StringBuilder
StringBuilder sb = new StringBuilder();
while (numb > 0) {
sb.append(numb % 10);
numb /= 10;
}
// and append the leading zeros.
System.out.println(sb + "0".repeat(len - exp));
for input of 00001000
prints 00010000
Note that you are still constrained on input by Integer.MAX_VALUE.
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;
}
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
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