Conversion int - binary
Hello everybody,
i want to change an integer signed value (on 32 bits) in binary format and do the reverse operation.
So i wrote :
String binIntStr = Integer.toBinaryString(-1610612462);
System.out.println("Binary : "+binIntStr);
System.out.println("Int : "+Integer.parseInt(binIntStr, 2));The conversion of the int to binary runs correctly, but the reverse operation (binary string to int) throws an NumberFormatException.
I don't understand why the operation is well done in one way and is not allowed in the other.
The integer value is in good format (-2147483648 < -1610612462 < 2147483647) so why can't I change the binary string returned by the method toBinaryString in an integer ?
Integer.toBinaryString() returns a string representation of the integer argument as an unsigned integer in base 2
from the API doc
toBinaryString
public static String toBinaryString(int i)Returns a string representation of the integer argument as an unsigned integer in base 2.
The unsigned integer value is the argument plus 232 if the argument is negative; otherwise it is equal to the argument.
This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0s. If the unsigned magnitude is zero, it is represented by a single zero character '0' ('\u0030');
otherwise, the first character of the representation of the unsigned magnitude will not be the zero character. The characters '0' ('\u0030') and '1' ('\u0031') are used as binary digits.
Parameters:
i - an integer to be converted to a string.
Returns:
the string representation of the unsigned integer value represented by the argument in binary (base 2).so you will have to figure out out to deal with signed values yourself
Message was edited by:
SomeoneElse
Similar Messages
-
Conversion of binary to number
Hello,
I have a signal conditioner controlled through serial communication with ASCII commands. Once the start command is received, there is a continuous stream of offset binary data sent and read through the serial Read Indicator. The manual informs me that I must first condition the offset binary values by subtracting 2048 from the raw values to produce a 2's complement value, it also mentions that the data is encoded in 12 bits so negative numbers must be properly sign extended to move the data into 16 bit words used by the PC. I am not familiar with binary numbers and am unsure on where to start. If someone could provide some insight and suggestions on what my first step would be to converting the binary values into number format, that would be greatly appreciated.
Thank you in advance,
JenaThat won't work because he's not receiving the string the way you think it is. The hex display is an interpretation of the underlying byte values. It is not the same as number written out in hex as a string. Your conversion assumes he's getting the character 1, followed by the character 8, followed by the character 0, followed by the character 0, followed by a space character.
The simplest way is to use the Type Cast function, 'cause that's what it's there for. Wire in an array of the datatype you want. The thing to keep in mind is that even though the data may be fundamentally 12 bits you need to deal with multiples of 8 because a serial read will read bytes, not bits. Thus, you can convert your string to an array of I16 numbers like this:
Message Edited by smercurio_fc on 04-08-2008 01:07 PM
Attachments:
Example_VI_BD2.png 2 KB -
Conversion from Binary to decimal - Need help
Hi guys,
I am new here and learnt some very basic Java before. I have a program that is in C++(to convert a binary number to decimal) that I found in the internet that interest me a lot. I am thinking whether this can be re-write in Java. I have tried to searh for solution but to no avail. I am wondering whether you guys can suggest a solution to this. Below are the source code in C++ :
#include <iostream.h>
#include <stdlib.h>
int main()
// part 1 : declaration
int Bin, Dec, TempBin;
int div;
char valid, again;
do {
// part 2 : Repeat asking the value of the binary number
Bin = TempBin = 0;
do {
cout << "Please input a binary number (1 to 10 bits) : ";
cin >> Bin;
TempBin = Bin;
do {
if ((TempBin % 10)==0 || (TempBin % 10)==1) // Note (1)
valid='Y';
else {
cout << "Invalid pattern! use 0's and 1's only\n\n";
valid='N';
break;
TempBin = (TempBin/10);
} while (TempBin>0);
} while (valid=='N');
// part 3 : Convertion
div = 1;
Dec = 0;
TempBin = Bin;
do {
Dec += (TempBin % 10)*div; // Note (2)
div *= 2;
TempBin = (TempBin/10);
} while (TempBin>0);
cout << "\nThe binary pattern " << Bin << " is equal to "
<< Dec << " in decimal pattern.\n" << endl;
// part 4 : try another number ?
cout << "\aTry another number (Y/N) : ";
cin >> again;
cout << "\n";
} while (again=='Y' || again=='y');
cout << "\n" << endl;
system("PAUSE");
return 0;
Appreciate your help. Thank you.
CKSo for Java, in your example, it takes a Java
String like "1001" and converts it to an int whose
value is one thousand and one. Can suggest a code for
this that takes user input str and convert to bin int.
I read books and noticed they are various ways to do
that. I am quite confused actually. It is like there
is no fix way to do that, unlike C++ which is more
easier to understand(in my opinion). Probably, because
I knew C better than Java.
The 'standard' way to take a String and convert it to an int...
int TempBin=Integer.parseInt(your_string);
You seem to be saying that you do not want to use the standard method, so you should not complain that there is no standard method. Here's some code that re-uses most of your modulo 10.
import java.io.*;
public class Test {
public static void main(String []args) throws IOException {
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
String result=null;
while(true) {
String input=bf.readLine().trim();
try {
long v=Long.parseLong(input);
result=toBin(v);
System.out.println(result);
} catch(NumberFormatException e) {
System.out.println("Only enter 1 or 0, nothing else!");
System.out.println();
public static String toBin(long btemp) {
long temp=btemp;
do {
if ((temp % 10)!=0 && (temp % 10)!=1) {
System.out.println("Invalid pattern! use 0's and 1's only\n\n");
return null;
temp = (temp/10);
} while (temp>0);
// part 3 : Convertion
int div = 1;
int Dec = 0;
long TempBin = btemp;
do {
Dec += (TempBin % 10)*div; // Note (2)
div *= 2;
TempBin = (TempBin/10);
} while (TempBin>0);
return ""+Dec; -
Conversion of binary string into headecimal
Ho will i convert binary string into hexadecimal fromat
HI,
Thanks but the above module is not present my system.
I have number which needs to be converted into binary first and then into Hex.
I have written it code for conversion of decimal number into Binary.But i am not able to convert it into Hex.
My rough code is ....
types : begin of t_temp,
r1 type i,
end of t_temp.
data : ty_temp type standard table of t_temp ,
wa_temp type t_temp.
DATA : num TYPE i,
temp1 TYPE string,
temp2 TYPE string,
temp3 TYPE string,
temp4 TYPE x.
temp1 = 0.
temp2 = ''.
num = 64.
while num ne 1.
temp1 = num MOD 2.
num = num / 2.
If temp1 = 1.
num = num - 1.
endif.
concatenate temp1 temp2 into temp2 .
endwhile.
temp1 = 1.
concatenate temp1 temp2 into temp2 .
condense temp2 no-gaps .
WRITE : temp2 . -
Hi,
I am facing a problem while converting data from Binary to Text format, I've used FM SCMS_BINARY_TO_TEXT but still there is no Output.
Can any1 please tell a FM which does the conversion??
Cheers
AbhishekFUNCTION MODULES
http://www.erpgenie.com/abap/functions.htm
http://www.sapdevelopment.co.uk/fmodules/fmssap.htm
http://www.erpgenie.com/abap/index.htm
http://www.geocities.com/victorav15/sapr3/abapfun.html -
I really need a bit of code that will convert an int to binary. Can anyone help me with this??
Cheers mark, certainly not how i had planned to do
it, was going to set up [32], store the remainder in
it, then read it backwards.I suppose you could do that, but it strikes me as sort of reinventing the wheel... :-)
Mark -
Conversion from Binary to oracle
I am in a great problem as I have to convert binary file in to the oracle database table but could not find a solution as I have the solution for the text file . So if anyone has any idea in this regard then Please help me out as soon as possible.I will be thankfull to your co-operation.
I just tested this in 10.1.2.2 on XP and could not reproduce the problem. It is unlikely that this is a bug and if it was, it is very likely that it was already corrected.
Ensure that you are using 6.0.8.26. If you are using Oracle Applications you should be using 6.0.8.27.
Also, Error Correction Support for stand-alone Forms 6.0.x users ended long ago, which means that a patch cannot be provided for version 6.x. -
Hello,
Oracle Info:
BANNER
Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production
PL/SQL Release 9.2.0.1.0 - Production
CORE 9.2.0.1.0 Production
TNS for 32-bit Windows: Version 9.2.0.1.0 - Production
NLSRTL Version 9.2.0.1.0 – Production
OS Info:
Microsoft Windows XP Professional Version 2002
Service Pack 1
Is there any PL/SQL code, by which we can convert numbers to its binary representation? Numbers can be something like these:
25,2008,-25,-2008,25.23,-25.23,2008.0701,-1715.1253 etc. (any number value)
Thanks & Regards
GirishSir, thanks for your compliments.
There is no limit for bit selection. If the number
fits in 8 bit then result should be in 8 bit
representation otherwise more required bits would be
there.Ok, consider I show you two binary numbers...
11001101
and
1001010010
Which one is positive and which one is negative?
Without stipulating the number of bits you are working with nobody can tell. This is a key requirement of working with postitive and negative integers.
As an example bring up Micro$ofts calculator in windows and ensure you have it set to scientific mode. Enter a simple negative number in decimal e.g. -5 and then click on the Bin radio button and look at the result...
1111111111111111111111111111111111111111111111111111111111111011
This is because Microsoft have stipulated that they are using 64 bit numbers, they don't just put 1011 or 11011 or 111011; all of which could be -5 but you can't be sure.
Suppose, I have created a table having 2
columns; first column will carry number value and
another column will carry binary representation
varchar2(4000) length. I am trying for this just for
increase PL/SQL programming skills and computer
fundamentals as well.Well as you know the 2's complement of negative numbers you should easily be able to write some SQL and/or PL/SQL that can give a string representation of the binary +ve and -ve number.
You're decimal numbers will be more difficult to represent as you need to determine if you are just going to use a binary representation of the number to the left and right of the decimal point and show that as binary with a decimal point in the equivalent place or whether you are going to reserve the lower X number of bits for the number to the right of the decimal point, or are you going to represent the whole number as a binary integer and store additional information giving the position of the decimal point (i.e. how much to divide by 10 is required)
Your choice. -
I want to retrieve the data of a ResultSet by rs.getInt(3), but I need to convert this data to an Integer, because my PrimaryKey is in Integer format. How could I retrieve an Integer?
Integer MyInteger = new Integer(rs.getInt(3));
I want to retrieve the data of a ResultSet by
rs.getInt(3), but I need to convert this data to an
Integer, because my PrimaryKey is in Integer format.
How could I retrieve an Integer? -
This is an information request from a complete coordinate systems newbie:
1. Does Oracle Spatial in 9.0.1 have an entry in MDSYS.CS_SRS that
corresponds to the coordinate system commonly known as "Earth Centered, Earth
Fixed" - where would I look (besides the table itself - I already tried that
with the 8.1.7 EE to no avail - it may be because I don't know enough about how
coordinate systems are referenced (the common nomenclature used) and just
didn't recognize it when I saw it.)
2. Are there any existing pl/sql snippets of code that can handle coordinate
conversions between ECEF-Lat/Long, geodetic degrees-decimal degrees? (If yes,
where should I go to look for them? By the way, please, please say yes, there
are many such packages just like there are for unit conversions (like binary to
hex).)
3. Where should I look to get information on a product called Map Viewer which
was mentioned in the latest edition of Oracle Magazine (May/June 2002, p.25 -
it was said to be a part of the 9iAS suite of products - I looked all over the
documentation but didn't find any mention of it.)
Thank you very much for your time and attention!
JulienThis is an information request from a complete coordinate systems newbie:
1. Does Oracle Spatial in 9.0.1 have an entry in MDSYS.CS_SRS that
corresponds to the coordinate system commonly known as "Earth Centered, Earth
Fixed" - where would I look (besides the table itself - I already tried that
with the 8.1.7 EE to no avail - it may be because I don't know enough about how
coordinate systems are referenced (the common nomenclature used) and just
didn't recognize it when I saw it.)
2. Are there any existing pl/sql snippets of code that can handle coordinate
conversions between ECEF-Lat/Long, geodetic degrees-decimal degrees? (If yes,
where should I go to look for them? By the way, please, please say yes, there
are many such packages just like there are for unit conversions (like binary to
hex).)You can get the proper params from the EPSG <http://www.epsg.org>,
I recall seeing some coord conversion samples in the tutorials/sample code - look in the OTN library
MArk -
Hi All,
Does anyone know any function module to convert 'image binary data' back to 'image' (bmp, jpeg..etc) format?
I appreciate any help.
Regards.
Edited by: mike curtis on Aug 12, 2010 9:10 PMhello mike .
I am facing with the similar problem that u have faced . I am very happy to see that your question has been answered.
Conversion of binary data into photo in sap. the binary data is of the same type as u faced , but still i am sending the data
FFD8FFE000104A46494600010101006000600000FFDB004300080606070605080707070909080A0C140D0C0B0B0C1912130F141D1A1F1E1D1A1C1C20242E2720
this data i need to convert into image (or) photo.
could you please help me in finding the solution for it. i will be very thankful and will be waiting for ur reply.
thanks in advance. -
Java Linear, Quicksort, Binary Time Calc Problems
Objective of program: Simple program demonstrating the time it takes to do each algorithm.
My approach:
1) Prompt a number
2) Make array of linear ints
3) Calculate time it takes for a linear search
4) Repeat for quick sort, and Binary search
Problems:
1) Linear search time is always 0
2) Quick sort never ends.
3) Don't know if binary works yet since it never goes beyond quicksort.
Any help or suggestions are greatly appreciated.
import java.util.Date;
import java.util.ArrayList;
import java.util.Random;
import java.util.Arrays;
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
Random generator = new Random();
int[] linear = new int[1000000]; // Create Linear Array
for(int i = 0; i < linear.length; i++) // filling up the array
linear[i] = i;
Scanner input = new Scanner(System.in);
System.out.print("Please enter number to search: "); // Asks
int search = input.nextInt(); // Stores number
Date end = new Date(); // Create Timer
long startTime1 = end.getTime(); // Start Time
for(int i = 0; i < linear.length; i++) { // Linear Search
if (linear[i] == search) {
long endTime1 = end.getTime(); // If found, end time
System.out.println("Time of Linear search: " + (endTime1 - startTime1)); // Prints elapsed time
break;
int[] quicksort = new int[1000000]; // Creates quicksort array
for(int i = 0; i < quicksort.length; i++) // Initializes the array
quicksort[i] = generator.nextInt(100000);
long startTime2 = end.getTime(); // Starts the time
for(int i = 0; i < 1000000; i++) // Sorts...
Arrays.sort(quicksort);
long endTime2 = end.getTime(); // Ends time
System.out.println("Time of QuickSort: " + (startTime2 - endTime2)); // Prints elapsed time
int[] binary = new int[1000000]; // Creates binary array
for(int i = 0; i < binary.length; i++) // Initializes binary array
binary[i] = generator.nextInt();
long startTime3 = end.getTime(); // Start time
Arrays.binarySearch(binary,search); // Binary Search
long endTime3 = end.getTime(); // Ends time
System.out.println("Time of Binary Search: " + (endTime3 - startTime3)); // Prints out time
}Edited by: onguy3n on Mar 26, 2009 4:39 AMibanezplayer85 wrote:
Any help or suggestions are greatly appreciated.
Suggestion: Break your code up into different methods and even separate classes, if necessary; don't just use main for everything. Maybe you posted it this way to have it all in one class for the forum to read, but it's very confusing to look at it and understand it this way. I know that this isn't an answer to your question, but you did ask for suggestions :)Thanks, it was just a demonstration program in class so he didn't really care about readability, but yes I should have separated it in a different class.
>
Linear search time is always 0I'm not sure what the convention is, but whenever I needed to measure time for an algorithm, I used System.currentTimeMillis(); rather than the Date class.
e.g.
long startTime = System.currentTimeMillis();
long endTime = System.currenTimeMillis();
long totalTime = endTime - startTime;Although, I think if you're not printing anything out to the console, it will most likely print out 0 as the time (because most of the processing is working on printing out the data). That is, unless you're doing some heavy processing.Thanks! I tried System.currentTimeMillis() and it now works. I still don't understand your explanation why it prints out 0 though :(
>
Quick sort never ends.I think it's just taking a while. It's not an efficient algorithm with a worst case time complexity of O(n^2) and you gave it a very large array of random values to work with. I wouldn't be surprised if you ran out of heap space before it finished. If you knock off some zero's on the array size, you'll see that it does, in fact, finish.Ok, thanks! In class we didn't talk much about the heap. How do I calculate how much heap space my program will use and how to allocate more? I vaguely remember something like xmx512m or something as the parameter, but every time I get an error:
Unrecognized option: -xmx512m
Could not create the Java virtual machine. -
Arrays,bubblesort, and binary search
Hi I need help I have been working on this homework assignment for the past week and I can't seem to get it so if anyone can help me to figure out what is wrong I would reall grateful. Thanks ahead of time for the help.
Here is what is required for the assignment and also the errors I am getting.
Thanks!
Write a program that sorts an integer array in ascending order and checks whether an integer entered by user is in the array or not. Please follow the following steps to complete the assignment:
1. Declare and create a one-dimensional array consisting of 20 integers.
2. Read 20 integers from the user to initialize the array. Use input dialog box and repetition statement.
3. Build an output string containing the content of the array.
4. Sort the array in ascending order using bubbleSort( ) and swap( ) methods. Then, append the content of the sorted array to the output string.
5. Read an integer search key from the user;
6. Use binarySearch( ) method to check whether the search key is in the array or not. Then, append the search result to the output string.
7. Display the output string in a message box.
Here is my code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SortSearch {
public static void main (String args[])
String input, ouput;
int key;
int index;
int[] array=new int [20];
input=JOptionPane.showInputDialog("Enter 20 Numbers");
for(int counter=0; counter<array.length; counter++)
output+=counter+"\t"+array[counter]+"\n";
array(counter)=Integer.parseInt(input);
JTextArea inputArea=new JTextArea();
outputArea.setText(output);
public void bubblesort(int array2[] )
for(int pass=1; pass<array2.length; pass++){
for(int element=0; element<array2.length-1; element++){
if(array2[element]>array2[element+1])
swap(array2, element, element+1);
public void swap(int array3[], int first, int second)
int hold;
hold=array3[first];
array3[first]=array3[second];
array3[second]=hold;
public void actionPerformed(ActionEvent actionEvent)
String searchKey=actionEvent.getActionCommand();
int element=binarySearch(array, Integer.parseInt(searchKey) );
if(element!=-1)
output.setText("Found value in element " + element);
else
output.setText("Value not found ");
public int binary search(iny array2[], int key)
int low=0;
int high=array2.length-1;
int middle;
while(low<=high){
middle=(low + high)/2;
buildOutput(array2, low, middle, high);
if(key==array[middle] )
return middle;
else if(key<array[middle] )
high=middle-1;
else
low=middle+1
return-1
JOptionPane.showMessageDialog(null, outputArea);
System.exit(0);
} //end main
} //end class
Here is my errors
C:\java>javac SortSearch.java
SortSearch.java:27: illegal start of expression
public void bubblesort(int array2[] )
^
SortSearch.java:20: cannot resolve symbol
symbol : variable output
location: class SortSearch
output+=counter+"\t"+array[counter]+"\n";
^
SortSearch.java:22: cannot resolve symbol
symbol : variable counter
location: class SortSearch
array(counter)=Integer.parseInt(input);
^
SortSearch.java:25: cannot resolve symbol
symbol : variable output
location: class SortSearch
outputArea.setText(output);
^
SortSearch.java:25: cannot resolve symbol
symbol : variable outputArea
location: class SortSearch
outputArea.setText(output);
^
5 errorsI am still having problems.
Here is my code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SortSearch {
public static void main (String args[]){
String input, output;
int key;
int index;
int[] array=new int [20];
input=JOptionPane.showInputDialog("Enter 20 Numbers");
for(int counter=0; counter<array.length; counter++)
array(counter)=Integer.parseInt(input);
JTextArea outputArea=new JTextArea();
outputArea.setText(output);
public void bubblesort(int array2[] )
for(int pass=1; pass<array2.length; pass++){
for(int element=0; element<array2.length-1; element++){
if(array2[element]>array2[element+1])
swap(array2, element, element+1);
} //end inner for
} //end outer for
} //end bubblesort
public void swap(int array3[], int first, int second)
int hold;
hold=array3[first];
array3[first]=array3[second];
array3[second]=hold;
} //end swap
public void actionPerformed(ActionEvent actionEvent)
String searchKey=actionEvent.getActionCommand();
int element=binarySearch(array, Integer.parseInt(searchKey) );
if(element!=-1)
outputArea.setText("Found value in element " + element);
else
outputArea.setText("Value not found ");
} //end actionperformed
JOptionPane.showMessageDialog(null, outputArea,"Comparisons");
} //end classHere is my errors
C:\java>javac SortSearch.java
SortSearch.java:57: <identifier> expected
JOptionPane.showMessageDialog(null, outputArea,"Comparisons");
^
SortSearch.java:57: cannot resolve symbol
symbol : class showMessageDialog
location: class javax.swing.JOptionPane
JOptionPane.showMessageDialog(null, outputArea,"Comparisons");
^
SortSearch.java:19: cannot resolve symbol
symbol : method array (int)
location: class SortSearch
array(counter)=Integer.parseInt(input);
^
SortSearch.java:49: cannot resolve symbol
symbol : variable array
location: class SortSearch
int element=binarySearch(array, Integer.parseInt(searchKey) );
^
SortSearch.java:52: cannot resolve symbol
symbol : variable outputArea
location: class SortSearch
outputArea.setText("Found value in element " + element);
^
SortSearch.java:54: cannot resolve symbol
symbol : variable outputArea
location: class SortSearch
outputArea.setText("Value not found ");
^
6 errors
Thanks ahead of time I still don't understand the stuff so I sometime don't understand what my errors are telling me so that is why I ask for your help so that maybe it will help make sense. -
hi,
to all am facing the problem in Conversion of binary data into photo in sap
FFD8FFE000104A46494600010101006000600000FFDB004300080606070605080707070909080A0C140D0C0B0B0C1912130F141D1A1F1E1D1A1C1C20242E2720
could you please help me in finding the solution for it. i will be very thankful and will be waiting for ur reply.
thanks in advance.Hi Praveen,
what is exactly the problem? (dump, the output isn't right,..)
what function are you using?
Please be more specific in order we can help you.
Regards!
Andrez. -
Greetings,
Is there another way that I can concatenate int to int. For eg,
I have int i = 12 and int x = 34 and I would like to get int result = 1234.
The one way of concatenating int to int is to convert both int to string, append them together and parse those string back to int. Is there any class or something that makes this approach little easier?. I am being very curious.
I realy appreciate your help. Thank You in Advance.
Regards,
Pinal.Use Strings and conversions.
int newInt = Integer.parseInt(
(String)(String.valueOf(firstInt) +
String.valueOf(secondInt)) );this is the very thing they are trying NOT to do...
<sarcasm>
i take it you read the entire thread?
</sarcasm>
Maybe you are looking for
-
Urgent!! How to capture the active windows
I want to write a program to capture the active windows in the Windows desktop. Can anyone help me. I know to use class "Robot" to capture the screen, but how to determine the position of the active windows in the desktop. Thanks...
-
(PS3)Changing NAT TYPE to Open for router WRT150N
I need help chaning the NAT Type to open because I can't play with some of my friends on Playstation. Tell me how please loans personal
-
HT1386 syncing more than one iPhone with iTunes
Is there a way to set up different profiles to sync more than one iPhones with the same iTunes? My wife doesn't want all my music, but she does want to share calanders. Any ideas?
-
can i protect with a code or something to open an app or a folder of apps in my iphone to avoid someone access them? tx
-
I downloaded Yosemite and now my iPhoto has a bar across it and will not open. I need to update to the latest version. The app store says the latest version is not available in the Canadian Store. What can I do.