Converting from binary to decimal
i writ this program to let the user input his number and then it will be converted to decimal,but how can i limited the rang of my digit,or if i want him to enter 4 digits only what can i do,,,and if i dont limit a range how can i make it?
this is my code
import javax.swing.JOptionPane;
public class Ch4_25
public static void main(String[]arg)
int F,d1,d2,d3,d4,num=1;
String N = JOptionPane.showInputDialog("Enter the number");
num=Integer.parseInt(N);
d1=num/10000;
num=num%10000;
d2=num/1000;
num=num%1000;
d3=num/100;
num=num%100;
d4=num/10;
F= d4*1+d3*2+d3*4+d2*8+d1*16;
JOptionPane.showMessageDialog(null,"the number is"+F);
System.exit(0);
}
Similar Messages
-
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; -
Vbs binary to decimal converter
I tried to use the following converter but it doesn`t work. Diadem says ')' expected in line 1. What is wrong with this code?
Option Explicit 'Erzwingt die explizite Deklaration aller Variablen in einem Script.
Public Function BinaryToDecimal(Binary As String) As Long
Dim n As Long
Dim s As Integer
For s = 1 To Len(Binary)
n = n + (Mid(Binary, Len(Binary) - s + 1, 1) * (2 ^ _
(s - 1)))
Next s
BinaryToDecimal = n
End Function
Public Function DecimalToBinary(DecimalNum As Long) As _
String
Dim tmp As String
Dim n As Long
n = DecimalNum
tmp = Trim(Str(n Mod 2))
n = n \ 2
Do While n <> 0
tmp = Trim(Str(n Mod 2)) & tmp
n = n \ 2
Loop
DecimalToBinary = tmp
End Function
Thanks in advance!Thanks for your solutions! I came a big step further through that.
Now I´m nearly at the solution. I wrote following programm.
The first part reads in special parts of a file from my pc into an array.
The second part converts the binary parts into hex-values. (here only meinArray(0), but I am going to insert a loop)
The third part converts the hex-values in 2`s complement into signed decimal values
The problem is only how to give the values from the second part into the third part. It doesn´t work with the following solution:
'first part
Dim fso, zeile, Textdatei, Zeichen1, Zeichen2, meinArray(128), i, txt
' Zugriff auf das Dateisysten
Set fso = CreateObject("Scripting.FileSystemObject")
Set Textdatei = fso.OpenTextFile("C:\Users\Christoph\Desktop\Projekt\11061543.003",1)
Textdatei.Skip(40960)
do
Zeichen1 = Textdatei.Read(1)
Zeichen2 = Textdatei.Read(1)
meinArray(i)= Zeichen2 & Zeichen1
i=i+1
loop while i<128
For i = LBound(meinArray) To UBound(meinArray)
txt = txt & meinArray(i) & vbCrLf
Next
MsgBox txt
'second part
Function StrToHex(Values) ' useful for debugging!
Dim j, k, TempVal, HexVals
IF NOT IsArray(Values) THEN
TempVal = Values
ReDim Values(0)
Values(0) = TempVal
END IF ' the Values input is a Scaler-- map to a 1 element Array
ReDim HexVals(UBound(Values))
FOR j = 0 TO UBound(Values)
HexVals(j) = ""
FOR k = 0 TO Len(Values(j))-1
HexVals(j) = HexVals(j) & Right("0" & Hex(Asc(Mid(Values(j), k+1, 1))), 2)
NEXT ' k
NEXT ' j
IF NOT IsEmpty(TempVal) THEN
TempVal = HexVals(0)
HexVals = TempVal
END IF ' the Values input was a Scaler-- return a Scaler
StrToHex = HexVals ' returns a Variant array of [Hex][Codes][in][each][Value()]
End Function ' StrToHex()
StrToHex(meinArray(0))
'third part
Function TwoComplement8Bits(StrToHex)
TwoComplement8Bits=CInt(StrToHex)
If TwoComplement8Bits>127 Then
TwoComplement8Bits=-1*((Not (TwoComplement8Bits Or &hff00))+1)
End If
End Function
MsgBox TwoComplement8Bits(StrToHex) -
Checking and Converting binary, octal, decimal, and hex
Hi,
I have a classroom project which will need to validate that data entered in a text is of a certain type with a keyListener, and then convert that value to the other 3 types.
I know character.isDigit will handle the decimal case, and that I can then use Integer.otString methods to convert to binary, octal, and hex, but what about the other cases?
ThanksOK, this isn't working. If I've already established
that the string entered into, for example, the
integer-only textfield is a valid integer, I should be
able to simply use integer.parseint(s, 2) to convert
it into binary, right?Not exactly. You should be able to use Integer.parseInt(s, 2) to return the result of converting it from binary representation. You appear to think that this affects whatever "s" refers to, which is not the case. Note also, that method returns an int which is the decimal value in question.
When you are thinking of int variables, be careful not to think of them as "decimal" or "binary". They are neither. They are just numbers. "Decimal" and "binary" are text representations of numbers, so those concepts can only be applied to strings.
Integer.parseInt(s, 2);
txtBin.setText(s);So here you want to assume that the input is a string that represents a number in decimal, and you want to find the string that represents the number in binary. Like this:// convert string in decimal representation to number
int dec = Integer.parseInt(s);
// convert int to binary representation as string:
String binary = Integer.toBinaryString(dec);
// write that to the text field
txtBin.setText(binary);You could use a one-liner to do that, but you'll need the "dec" variable to set the other text boxes.
Rembering why I hate OO...All of what I said there is true in just about all computer languages, OO or otherwise.
PC² -
Need to convert a binary value into decimal
Hi i need to convert a binary value which i would be getting as a string object to a decimal value......need code for the same
Check Integer.parseInt
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Integer.html#parseInt(java.lang.String,%20int) -
How could I choose some bytes from HEX string and then convert it to a decimal value?
Hi I am working with an OMRON E5EN temperature controller using VISA serial to get data, I send the Read from Variable Area command and get this string in hexa 0230 3130 3030 3030 3130 3130 3030 3030 3030 3030 3041 3203 71 or .01000001010000000000A2.q in ASCII this string means:
02 STX
3031 3030 Node and subadress
3030 End Code Normal Completion
3031 3031 Command Read from Variable Area
3030 3030 respt code Normal completion
3030 3030 3030 4132 Hexadecimal A2 = 162 (this is the temperature data that I want to show in decimal)
03 ETX
71 Block Check Character
I want to choose the eight bytes for the temperature data and convert it to a decimal number. I have seen the examples to convert a Hexa string to decimal but I do not know how to choose the specifics bytes that I need.
I have look for a driver but i didn´t find any. I am a beginner so please include especific topics for me to study in your answer.
Thanks
Carlos Fuentes Silva Queretaro MexicoIf the response always has the temperature starting with byte 15 and is always 8 bytes in length, you can use the String Subset function to get those bytes out of the string. Then use Hex String to Number to convert to a decimal number.
Well someone already beat me to the solution:
Message Edited by tbob on 01-04-2008 04:42 PM
- tbob
Inventor of the WORM Global
Attachments:
HexStr2Decimal.png 7 KB -
Convert from Comma notation to Decimal Notation, Any FM ?
Hi Experts,
I am looking to convert from Europe format to US format for Quantity & amount fields, I mean
e.g. Europe: 12.3456,78 -> US: 12,3456.78
pls. i can not use offsetting, replace, pattern, overlay, concatenate etc.
So, pls. let me know that, Is there any SAP FM for this purpose of DECIMAL NOTATION conversion?
thanq
Edited by: Srinivas on Feb 22, 2008 10:48 PMuse.
Replace all occurances of ',' in w_value with '.'.
Check this thread.
REgarding converting ',' TO '.' -
Help converting binary to decimal.
Hi all.
I'm taking a course in Java programming and so far its been a great experience. I'm currently stumped on one of my assignments and I am kindly requesting some assistance.
Basically I have to convert a binary entry into its decimal comparison.
so for instance an entry of 1101 would output 13.
I have the calculation formula, but my problem is finding out whether the point i'm looking at is either a 1 or a 0. I can't seem to 'strip it down' to the value.
My current thought is something like this:
binary = 1101;
// problem is here
thou = (binary % 1000) / 1000;
hund = (thou % 100) / 100;
tens = (hund % 10) / 10;
ones = (tens % 1) / 1;
// then do formular
decimal = ones * 1 + tens * 2 + hund * 4 + thou * 8;
I have searched but all the suggestions say to use a custom function or other obscure method. I don't know that stuff real well and we aren't even that far in the book either. All we've done so far is while, if .. else, condition statements.
I will include the actual text for the question, in case i'm not clear. This text also includes a 'tip' which isn't helping me. (http://www.geocities.com/kaveman2000/q-4-25.pdf)
Thanks again for any pointers.angeles1016 (and all),
thanks for your great help and code snippets.
angeles1016,
using the code you provided i noticed that the last (single digit) was giving the wrong response in certain cases. (1000, 0111, 0001, ..) i could be off one.
either way, i decided to fix it up and give you all the update.
// do class, main function stuff
if(binary/1000 == 1){
thousands += (binary/1000);
temp = binary % 1000;
if(temp/100 == 1){
hundreds += (temp/100);
temp = temp % 100;
if(temp/10 == 1){
tens += (temp/10);
temp = temp % 10;
if(temp/1 == 1){
ones += (temp/1);
// calculate binary to decimal
decimal = (ones * 1) + (tens * 2) + (hundreds * 4) + (thousands * 8);
// take result and convert to string for output
result += "Decimal: " + decimal + "\n";
// display in gui ?
// end function and class stuff(note: i suppose the statements similar to "thousands += (binary/1000);" can be simplified as "thousands = 1;") -
Hi All,
I want to convert from decimal (5, 2) to decimal (3,0) in data services.
if anybody knows please let me know with syntax.https://scn.sap.com/community/data-services/blog/2013/06/12/conversion-functions-in-bods-with-examplespart3
https://scn.sap.com/community/data-services/blog/2013/06/12/conversion-function-in-bods-with-examplespart3 -
Required code to convert binary to decimal
i need the programming logic to convert a binary number into its decimal equivalent. the program should also detect a non binary number.
public class EnterBinary{
public static void main (String []args){
int binCheck=0;
String bins="";
try {
bins=args[0];
catch (Exception e){
System.out.print("No user input, program will terminate");
System.exit(0);
for(int i=0; i<bins.length(); i++)
if((bins.charAt(i)=='1')||(bins.charAt(i)=='0')) binCheck++;
if(binCheck==bins.length() ) {
int j=1;
binCheck=0;
for(int i=0; i<bins.length()-1; i++) j *=2;
for(int i=0; i<bins.length(); i++){
if(bins.charAt(i)=='1') binCheck += j;
j /=2;
System.out.print("The binay number "+bins+" in decimal is "+binCheck);
else System.out.print("Invalid binary input, program will terminate");
} -
Convert a channel from Hexidecimal to Decimal
Is there an easy way to convert a channel from HEX to Decimal without having to change every individual measurement.
I am currently using the following command:
HEXnumCOVNVERTED = (CLng("&h" & HEXnumTOconvert))
Just curious if there was an easier way around this.
BBANACKISure,
and you can use the same command for it. Simply use the DIAdem Calculator, which is capable of doing the calculation for a complete channel - row by row.
The syntax would be something like: ch("dec") = CLng("&h" & ch(1))
In the formula, replace Ch(1) with the channel you would like to convert.
Ingo Schumacher
Systems Engineer Sound&VibrationNational Instruments Germany -
Convert between binary and signed/unsigned decimal numbers
Hi all,
Has anyone written a code to convert:
binary number --> signed decimal
binary number --> unsiged decimal
signed decimal --> binary
unsigned decimal --> binary
Please help! I'm confusing.http://java.sun.com/j2se/1.4/docs/api/java/lang/Integer.html
See the methods parseInt and toBinaryString.
Please help! I'm confusing. You are, aren't you?
(Sorry, couldn't resist...) -
Convert hexadecimal output to decimal (number)
I am reading hexadecimal format from the output of the VISA read block and I want to convert it to the decimal preferably exponential format.
Example of what I read is 76 00 02 (in dec: 7.600 E+2).
I know there is "type cast" block that converts nicelly but I am not sure what to specify for a type input.
Can you show me how to apply this type cast block for in my VI so that it converts hex string (76 00 02) into exponential string/number (7.600 E+2)?
I attached my VI so it is more clear.
Thanks everybody,
Pedja
Attachments:
MultiGauge.vi 64 KBCoop wrote:
> I am reading hexadecimal format from the output of the VISA read block
> and I want to convert it to the decimal preferably exponential format.
> Example of what I read is 76 00 02 (in dec: 7.600 E+2).
> I know there is "type cast" block that converts nicelly but I am not
> sure what to specify for a type input.
> Can you show me how to apply this type cast block for in my VI so that
> it converts hex string (76 00 02) into exponential string/number
> (7.600 E+2)?
Looking at your code I see that you have not a hexadecimal string coming
back but instead a binary string. The fact that you display the string
as hexadecimal in the string indicator is just showing you the ASCII
codes of the string characters as hexadecimal numbers.
The funct
ion From Hexadecimal String expects a clear text string with
hexadecimal characters but that is something entirely different from a
binary string you choose to display as hexadecimal numbers.
An example: the binary string 7600 02 you receive from the device is in
fact the character 'v', a null character and a 02 character (or in ASCII
terms a start of text character).
So assuming your example is right (which I have to admit seems very
strange and therefore suspicious to me) you would have to do something
more like included example. But as I said I have little understanding
why the hexadecimal interpretation of the binary values should
correspond to the decimal value you want to have!
Also as you can see there is not really clear where the 00 character
belongs to. The two methods where it is either part of the multiplier or
the exponent both produce the same result for this particular example.
Which one is right if any, should be tested.
Rolf Kalbermatter
Rolf Kalbermatter
CIT Engineering Netherlands
a division of Test & Measurement Solutions
Attachments:
Binary_(Hex)_to_Decimal_Numeric.vi 51 KB -
Hi i am having trouble from converting a binary number into decimal. I found the following code from a tutorial online and would like to merge it inside the code i currently have.
This is the example i found online:
//initialize the place values
var place:Array = [32, 16, 8, 4, 2, 1];
//initialize your binary number
var binary:Array = [1, 1, 0, 0, 1, 1];
//trace it as a string
trace(binary.join(""));
//convert it to a decimal number
var decimalNumber = (place[0]*binary[0])+(place[1]*binary[1])+(place[2]*binary[2])+(place[3]*binary[3])+(place[4]*binary[4])+(place[5]*binary[5]);
//trace the result
trace(decimalNumber);
This is the code i currently have
var binaryArray:Array = new Array();
var num:Number;
var binaryString:String;
var round:Number;
var bString:String;
var bNumber:Number;
decimal_txt.addEventListener(KeyboardEvent.KEY_DOWN, checkEnterKey);
function checkEnterKey(e:KeyboardEvent):void
if(decimal_txt.text != '' && e.keyCode == Keyboard.ENTER)
num = Number(decimal_txt.text);
//trace(e.keyCode + " : " + tf.text);
bString = convertDecimalToBinary(num);
bNumber = Number(binaryString);
binary_txt.text = bString;
function getTextInput(e:KeyboardEvent):void
num = Number(decimal_txt.text);
//trace(e.keyCode + " : " + tf.text);
bString = convertDecimalToBinary(num);
bNumber = Number(binaryString);
binary_txt.text = bString;
function convertDecimalToBinary(num:Number):String
if(num == 0)
return String("");
binaryString = ''; //starts with an empty string
while(num > 0)
num /= 2;
if(Math.floor(num) == num)
binaryArray.push(0);
else
binaryArray.push(1);
trace(num);
num = Math.floor(num);
for(var i:int = binaryArray.length-1; i >= 0; i--)
binaryString += binaryArray[i];
// clear array to prepare for next input
binaryArray.pop();
while (binaryString.length<8) {
binaryString = "0"+binaryString;
//trace(binaryString);
return binaryString;
However the first code already sets a decimal value in the array and calculates it but i would like to merge it with the one i have which outputs the decimal value from an input of a binary number. How would this be possible?what output?
all you're doing is defining n when a key is down. you're not doing anything with n so i don't see how you expect any output.
if binary_txt is a textfield with a binary (string) and decimal_txt is a textfield that should display the decimal representation of binary_txt.text, use:
binary_txt.addEventListener(KeyboardEvent.KEY_DOWN, checkEnterKey2);
function checkEnterKey2(e:KeyboardEvent):void{
if(binary_txt.text != '' && e.keyCode == Keyboard.ENTER){
decimal_txt.text=binaryToDecimal(binary_txt.text);
function binaryToDecimal(s:String):Number{
for(var i:int=0;i<s.length;i++){
n+=Number(s.substr(i,1))<<(s.length-1-i)
return n; -
Hi,
I have a question.
How do I convert from String to Integer?
Here is my code:
try{
String s="000111010101001101101010";
int q=Integer.parseInt(s);
answerStr = String.valueOf(q);
catch (NumberFormatException e)
answerStr="Error";
but, everytime when i run the code, i always get the ERROR.
is the value that i got, cannot be converted to int?
i've done the same thing in c, and its working fine.
thanks..6kyAngel wrote:
actually it convert the string value into decimal value.In fact what it does is convert the (binary) string into an integer value. It's the String representation of integer quantities that have a base (two, ten, hex etc): the quantities themselves don't have a base.
To take an integer quantity (in the form of an int) and convert it to a binary String, use the handy toString() method in the Integer class - like your other conversion, use the one that takes a radix argument.
Maybe you are looking for
-
Need to report on sales order lines using specific pricing modifier
Is there a report I can run for a specific modifier number that will give me all the sales order lines that were adjusted using that pricing modifier?
-
Tagging Facebook albums created in Aperture not working
I'm trying to publish a Facebook album from within Aperture (3.6), and am having trouble getting the tags to stick in Facebook. When I go visit the album on Facebook, the tags are there, but not actually linked to the people. For example My friend Jo
-
Waterproof cases for muvo tx fm or na
i think creative should make some waterproof cases esp for their small form mp3 players like iri'ver...would anyone buy one if they made some because i would...
-
Version Management on SAP Script Forms
Hello, Is there a version management for SAP Script forms like what we have in ABAP programs? I need to revert back the old version of my SAP scrip form like what I used to do in an ordinary ABAP program. Is this possible? Need your views on this
-
Error -- User doesnot belong to required Roles
Hi All, When I am trying to loginto Infoview or CMC I get Error "User does not belong to any of the required roles -- DX1003@SAP_J2EE_ADMIN;QB1142@SAP_J2EE_ADMIN(EAS 10005)" I am using BOXIR.3.1, SAP 7.1 Pls. let me know what are the exact roles in w