Converting from Int to Hex in Delphi and Java - java

I have to convert the following Delphi code to Java:
function IntToHex(MyValue: Integer; MinimumWidth: Integer): Ansistring;
begin
AnsiStrings.FmtStr(Result, '%.*x', [MyValue, MinimumWidth]);
end;
The IntToHex function converts a DecimalValue integer into a hexadecimal format string of at least MinimumWidth characters wide.
I've implemented it in Java as:
public static String intToHex(int value)
{
return Integer.toHexString(value);
}
Do I need in Java to indicate that the resulting string must contain at least the specified number of digits like in Delphi with parameter MinimumWidth?
Did I already with my Java function implemented the full functionality from the Delphi IntToHeX-function?

If I correctly understand your question, I think your solution should be to use String.format in Java
If you want hex numbers in the string you can use
String myFormattedString = String.format("%x", mynumber);
You can specify the lenght prepending it to the x, as
String myFormattedString = String.format("%4x", mynumber);
Where of course mynumber is a int or any other kind of valid number.
If you want to pad with zeros you should use
String myFormattedString = String.format("%04x", mynumber);
You can use capital X to have capital letters in the resulting String
To have more information on the format option you can take a look at the following URL: http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax
Hope this can help

Related

Is there any method like char At in Dart?

String name = "Jack";
char letter = name.charAt(0);
System.out.println(letter);
You know this is a java method charAt that it gives you a character of a String just by telling the index of the String. I'm asking for a method like this in Dart, does Dart have a method like that?
You can use String.operator[].
String name = "Jack";
String letter = name[0];
print(letter);
Note that this operates on UTF-16 code units, not on Unicode code points nor on grapheme clusters. Also note that Dart does not have a char type, so you'll end up with another String.
If you need to operate on arbitrary Unicode strings, then you should use package:characters and do:
String name = "Jack";
Characters letter = name.characters.characterAt(0);
print(letter);
Dart has two operations that match the Java behavior, because Java prints integers of the type char specially.
Dart has String.codeUnitAt, which does the same as Java's charAt: Returns an integer representing the UTF-16 code unit at that position in the string.
If you print that in Dart, or add it to a StringBuffer, it's just an integer, so print("Jack".codeUnitAt(0)) prints 74.
The other operations is String.operator[], which returns a single-code-unit String. So print("Jack"[0]) prints J.
Both should be used very judiciously, since many Unicode characters are not just a single code unit. You can use String.runes to get code points or String.characters from package characters to get grapheme clusters (which is usually what you should be using, unless you happen to know text is ASCII only.)
You can use
String.substring(int startIndex, [ int endIndex ])
Example --
void main(){
String s = "hello";
print(s.substring(1, 2));
}
Output
e
Note that , endIndex is one greater than startIndex, and the char which is returned is present at startIndex.

Java - Construct a signed numeric String and convert it to an integer

Can I somehow prepend a minus sign to a numeric String and convert it into an int?
In example:
If I have 2 Strings :
String x="-";
String y="2";
how can i get them converted to an Int which value is -2?
You will first have to concatenate both Strings since - is not a valid integer character an sich. It is however acceptable when it's used together with an integer value to denote a negative value.
Therefore this will print -2 the way you want it:
String x = "-";
String y = "2";
int i = Integer.parseInt(x + y);
System.out.println(i);
Note that the x + y is used to concatenate 2 Strings and not an arithmetic operation.
Integer.valueOf("-") will throw a NumberFormatException because "-" by itself isn't a number. If you did "-1", however, you would receive the expected value of -1.
If you're trying to get a character code, use the following:
(int) "-".charAt(0);
charAt() returns a char value at a specific index, which is a two-byte unicode value that is, for all intensive purposes, an integer.

(JAVA) how to use charAt() to find last digit number (or rightmost) of any real number?

Hello Im new to programming
and as title I was wonder how you can find last digit of any given number?
for example when entering in 5.51123123 it will display 3
All I know is I should use charAt
Should I use while loop?
thanks in advance
You would want to do something like this:
double number = 5.51123123;
String numString = number + "";
System.out.println(numString.charAt(numString.length()-1));
When you do the number + "", Java "coerces" the type of number from a double to a string and allows you to perform string functions on it.
The numString.length()-1 is because numString.length() returns the count of all the characters in the string BUT charAt() indexes into the string and its indexing begins at 0, so you need to do the -1 or you'll get a StringIndexOutOfBoundsException.
You can use below function simply and you can customize data types accordingly,
private int getLastDigit(double val){
String tmp = String.valueOf(val);
return Integer.parseInt(tmp.substring(tmp.length()-1));
}
You can't use charAt on a floating point variable (or any other data type other than Strings). (Unless you define a charAt method for your own classes...)
You can, however, convert that floating point number to a string and check the charAt(str.length()-1).
Convert your float variable to string and use charAt(strVar.length - 1).
double a=5.51123123;
String strVar=String.valueOf(a);
System.out.print(strVar.charAt(strVar.length -1);
Double doubleNo = 5.51123123;
String stringNo = doubleNo.toString();
System.out.println(stringNo.charAt(stringNo.length()-1));

Character Concatenation Resulting in Numerical Output [duplicate]

This question already has answers here:
In Java, is the result of the addition of two chars an int or a char?
(8 answers)
Closed 9 years ago.
In a programming language called Java, I have the following line of code:
char u = 'U';
System.out.print(u + 'X');
This statement results in an output like this:
173
Instead of
UX
Am I missing something? Why isn't it outputing 'UX'? Thank you.
Because you are performing an addition of chars. In Java, when you add chars, they are first converted to integers. In your case, the ASCII code of U is 85 and the code for X is 88.
And you print the sum, which is 173.
If you want to concatenate the chars, you can do, for example:
System.out.print("" + u + 'X');
Now the + is not a char addition any more, it becomes a String concatenation (because the first parameter "" is a String).
You could also create the String from its characters:
char[] characters = {u, 'X'};
System.out.print(new String(characters));
In this language known as Java, the result of adding two chars, shorts, or bytes is an int.
Thus, the integer value of U (85) is added to the integer value of X (88) and you get an integer value of 173 (85+88).
To Fix:
You'll probably want to make u a string. A string plus a char will be a string, as will a string plus a string.
String u = "U"; // u is a string
System.out.print(u + 'X'); // string plus a char is a string
String u = "U";
System.out.print(u + "X");
instead of char type use String class or StringBuilder class
Another way to convert one of the characters to a string:
char u = 'U';
System.out.print(Character.toString(u) + 'X');
This way could be useful when your variable is of type char for a good reason and you can't easily redeclare it as a String.
That "language called Java" bit amused me.
A quick search for "java concatenate" (which I recommend you do now and every time you have a question) revealed that most good Java programmers hate using + for concatenation. Even if it isn't used numerically when you want string concatenation, like in your code, it is also slow.
It seems that a much better way is to create a StringBuffer object and then call its append method for each string you want to be concatenated to it. See here: http://www.ibm.com/developerworks/websphere/library/bestpractices/string_concatenation.html

Pad digits until string is 8 chars long in java?

i was reading and couldn't find quite the snippet. I am looking for a function that takes in a string and left pads zeros (0) until the entire string is 8 digits long. All the other snippets i find only lets the integer control how much to pad and not how much to pad until the entire string is x digits long. in java.
Example
BC238 => 000BC289
4 => 00000004
etc thanks.
If you're starting with a string that you know is <= 8 characters long, you can do something like this:
s = "00000000".substring(0, 8 - s.length()) + s;
Actually, this works as well:
s = "00000000".substring(s.length()) + s;
If you're not sure that s is at most 8 characters long, you need to test it before using either of the above (or use Math.min(8, s.length()) or be prepared to catch an IndexOutOfBoundsException).
If you're starting with an integer and want to convert it to hex with padding, you can do this:
String s = String.format("%08x", Integer.valueOf(val));
org.apache.commons.lang.StringUtils.leftPad(String str, int size, char padChar)
You can take a look here
How about this:
s = (s.length()) < 8 ? ("00000000".substring(s.length()) + s) : s;
or
s = "00000000".substring(Math.min(8, s.length())) + s;
I prefer using an existing library method though, such as a method from Apache Commons StringUtils, or String.format(...). The intent of your code is clearer if you use a library method, assuming it is has a sensible name.
The lazy way is to use something like: Right("00000000" + yourstring, 8) with simple implementations of the Right function available here: http://geekswithblogs.net/congsuco/archive/2005/07/07/45607.aspx

Categories

Resources