Related
Example:
a = "100"
b = "11"
Return a + b = “111”.
its done by parsing int but when two strings are more then int size then it will not working.
i tried with long :
long a1=Long.parseLong(a,2);
long b1=Long.parseLong(b,2);
long sum=a1+b1;
String ans=Long.toBinaryString(sum);
is there any methods for double??
To exceed the long size you will need BigInteger.
public void test() {
String a = "100";
String b = "11";
BigInteger bA = new BigInteger(a, 2);
BigInteger bB = new BigInteger(b, 2);
System.out.println(a + " + " + b + " = " + bA.add(bB).toString(2));
}
This does not help with double though.
For double you can try this:
double number = 2.2;
Long.toBinaryString(Double.doubleToLongBits(number));
https://stackoverflow.com/a/8272792/6049590
Copied and modified from above Source
public double ConvertToDouble(string str){
long v = 0;
for (int i = str.Length - 1; i >= 0; i--) v = (v << 1) + (str[i] - '0');
return = BitConverter.ToDouble(BitConverter.GetBytes(v), 0);
}
https://social.msdn.microsoft.com/Forums/vstudio/en-US/0ff76c9a-8d8c-46f3-94cc-420f719a14e4/how-to-convert-floatdoubleulong-into-binaryotcalhex-string?forum=netfxbcl
Copied and modified from above Source
public string ConvertToString(double value){
string s = String.Empty;
foreach (byte b in BitConverter.GetBytes(value))
{
s += Convert.ToString(b,2).PadLeft(8,'0'); // for hex. For binary, use 2 and 8. For octal, use 8 and 3
}
return s;
}
And now the last one:
double c = ConvertToDouble(a) + ConvertToDouble(b);
string bitString = ConvertToString(c);
string bitString should be your expected result.
For adding then converting String again :
public String XXX()
{
int a = Double.parseDouble("100.0");
int b = Double.parseDouble("11.0");
return (a + b) + "";
}
For adding then returning :
public double XXX()
{
int a = Double.parseDouble("100.0");
int b = Double.parseDouble("11.0");
return (a + b);
}
Have a nice day!
If the strings are too long to fit any of the standard types and you don't want to use BigInteger, then you can do it the old-fashioned way using the same algorithm you use when adding two numbers by hand, on paper.
For example, if you have "110" and "11", you would write:
110
+ 11
----
Then you start from the right and move left, adding the digits. Your first partial result is "1", in the right-hand column:
110
+ 11
----
1
Next, "1" and "1" is "0", with a carry of "1". So you write the "0" and note that you have a carry. Your partial result is "01", with the carry.
In the third column you add the "1" and the carry, again giving you "0" with a carry. Your partial result is "001" and the carry. In the fourth column you add the carry, giving you the final result, "1001".
To do that in code, the easiest thing is to pad the shorter number with "0" on the left so that it's the same length as the longer number. So in the example above I would have turned the "11" into "011". Then write a loop that will process the strings from right to left. I'm not a Java programmer, but you should be able to get the idea from this pseudocode.
number1 = "110"
number2 = "011"
result = ""
carry = 0
for i = length(number1) downto 0
digit1 = number1[i].ToInt()
digit2 = number2[i].ToInt()
sum = digit1 + digit2 + carry
if (sum % 2) == 0
result = result + "0"
else
result = result + "1"
carry = (result > 1)
end for
if (carry = 1)
result = result + "1"
That's the slow and simple way to do it. You can use a variation of that method to do it much faster. Basically, you take the bits 32 at a time (from right to left), do the addition, output the resulting 32 bits, maintain the carry (if any), and then move left. You can do that with bytes, words, ints, or longs. Say you're doing it with bytes and your numbers are "010101010101010101010101" and "10110100110101001111". You would split them into 8-bit groups:
3 2 1
01010101 01010101 01010101
10110100 11010100 11111100
Grab the two bytes from group 1, convert them to int, add them, and output the first 8 bits of the result. If there is a ninth bit to the result (there can't be more than 9 bits), then it's a carry into the next column of numbers.
Continue that until you've finished the last column of numbers. As I said, you can do that with any integral type (byte, short, int, long) to speed up the basic algorithm I laid out for individual bits.
I am trying to solve this problem and I think I am in the right track but for some reason the program does not run in a specific condition.
This is the code:
public class Eight {
public static void main(String[] args) {
String set = "731671765313306249192251196744265747423"
+ "553491949349698352031277450632623957831801698"
+ "480186947885184385861560789112949495459501737958"
+ "331952853208805511125406987471585238630507156932909"
+ "632952274430435576689664895044524452316173185640309871"
+ "112172238311362229893423380308135336276614282806444486645"
+ "238749303589072962904915604407723907138105158593079608"
+ "66701724271218839987979087922749219016997208880937"
+ "7665727333001053367881220235421809751254540594752"
+ "243525849077116705560136048395864467063244157221"
+ "55397536978179778461740649551492908625693219784"
+ "686224828397224137565705605749026140797296865"
+ "241453510047482166370484403199890008895243450"
+ "6585412275886668811642717147992444292823086346567481391912316282458617866458"
+ "3591245665294765456828489128831426076900422421902267105562632111110937054421750694165"
+ "8960408071984038509624554443629812309878799272442849091888458015616609791913387549920052"
+ "4063689912560717606058861164671094050775410022569831552000559357297257163626956188267042"
+ "8252483600823257530420752963450";
int initialIndex = 0;
int lastIndex = 4;
int finale = 0;
for (;last <= set.length() - 1; initialIndex++, lastIndex++)
{
int num = Integer.parseInt(set.substring(initialIndex, lastIndex));
int result = 1;
while (num > 0)
{
int digit = num % 10;
result *= digit;
num /= 10;
}
if (result > finale)
finale = result;
} //end for
System.out.println(finale);
}
}
When lastIndex equals 4, the result I get is 5832, which is the same result as Project Euler gives you as an example. But when Im trying to run this program with 13 numbers instead of 4, I get an exception and the program does not run.
A 13 digit string will exceed the maximum allowable size of an int. Use Long.parseLong and change num from int to long. I did it, and got the following when I used 13 digits: 2091059712
Your issue begins here:
int num = Integer.parseInt(set.substring(initialIndex, lastIndex));
When you set lastIndex as 13, the number you are trying to take out of the string is 7,316,717,653,133. In your code, you are trying to parse that String as an int, which has a maximum value of 2^31 2,147,483,647.
You can fix your problem by making any variable you expect to excede 2^31 a different integral data type, like a long.
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);
}
}
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
I am calculating the int equivalent of a given set of bits and storing that in memory. From there, I would like to determine all 1 value bits from the original bitmask. Example:
33 --> [1,6]
97 --> [1,6,7]
Ideas for an implementation in Java?
On BitSet
Use java.util.BitSet to store, well, a set of bits.
Here's how you can convert from an int to a BitSet, based on which bits in the int is set:
static BitSet fromInt(int num) {
BitSet bs = new BitSet();
for (int k = 0; k < Integer.SIZE; k++) {
if (((num >> k) & 1) == 1) {
bs.set(k);
}
}
return bs;
}
So now you can do the following:
System.out.println(fromInt(33)); // prints "{0, 5}"
System.out.println(fromInt(97)); // prints "{0, 5, 6}"
And just for completeness, here's the reverse transformation:
static int toInt(BitSet bs) {
int num = 0;
for (int k = -1; (k = bs.nextSetBit(k + 1)) != -1; ) {
num |= (1 << k);
}
return num;
}
So composing both together, we always get back the original number:
System.out.println(toInt(fromInt(33))); // prints "33"
System.out.println(toInt(fromInt(97))); // prints "97"
On 0-based indexing
Note that this uses 0-based indexing, which is the more commonly used indexing for bits (and most everything else in Java). This is also more correct. In the following, ^ denotes exponentiation:
33 = 2^0 + 2^5 = 1 + 32 97 = 2^0 + 2^5 + 2^6 = 1 + 32 + 64
33 -> {0, 5} 97 -> {0, 5, 6}
If you insist on using 1-based indexing, however, you can use bs.set(k+1); and (1 << (k-1)) in the above snippets. I would advise strongly against this recommendation, however.
Related questions
What does the ^ operator do in Java? -- it's actually not exponentiation
For bit fiddling, java.lang.Integer has some very helpful static methods. Try this code as a starting base for your problem:
public int[] extractBitNumbers(int value) {
// determine how many ones are in value
int bitCount = Integer.bitCount(value);
// allocate storage
int[] oneBits = new int[bitCount];
int putIndex = 0;
// loop until no more bits are set
while (value != 0) {
// find the number of the lowest set bit
int bitNo = Integer.numberOfTrailingZeros(value);
// store the bit number in array
oneBits[putIndex++] = bitNo+1;
// clear the bit we just processed from the value
value &= ~(1 << bitNo);
}
return oneBits;
}
I can show you C# implementation, Java should be very similar.
int value = 33;
int index = 1;
while (value > 0)
{
if ((value % 2) == 1)
Console.WriteLine(index);
index++;
value /= 2;
}
If you want to get an array like that you'll likely need to loop the number of bits you want to check & the integer with a bit shifted 1 for each step.
Something like (pseudo):
Init array
mask = 1
for (0 to BitCount):
if Integer & mask
array[] = pos
mask << 1
A bit-crunching variation would be something like:
int[] getBits(int value) {
int bitValue = 1;
int index = 1;
int[] bits = new int[33];
while (value >= bitValue)
{
bits[index++] = (value & bitValue);
bitValue << 1; // or: bitValue *= 2;
}
return bits;
}
Note that since the bits are indexed from 1 as you requested, bits[0] is left unused.