converting the input string as a hexa number representation - java

I take a string like "abcd" as a command line argument in my java code. I need to pass this string to my C JNI code which should take this string and use it as a shared memory identity.
I am looking to know how and where I can make this string to be representing a hexa value.

Java or C? In C, you use strtoul:
#include <stdlib.h>
int main(int argc, char * argv[])
{
if (argc > 1)
{
unsigned int n = strtoul(argv[1], NULL, 16);
}
}
Check the manual; when parsing user input it's vital to check for errors, and there are several aspects to this when using strtoul.

Have you tried something like that:
final String myTest = "abcdef";
for (final char c : myTest.toCharArray()) {
System.out.printf("%h\n", c);
}
If that's what you are looking for, you can have a look at the printf method, it's based on Formatter

All you need is:
Integer.parseInt("abcd", 16);

public class HexString {
public static String stringToHex(String base)
{
StringBuffer buffer = new StringBuffer();
int intValue;
for(int x = 0; x < base.length(); x++)
{
int cursor = 0;
intValue = base.charAt(x);
String binaryChar = new String(Integer.toBinaryString(base.charAt(x)));
for(int i = 0; i < binaryChar.length(); i++)
{
if(binaryChar.charAt(i) == '1')
{
cursor += 1;
}
}
if((cursor % 2) > 0)
{
intValue += 128;
}
buffer.append(Integer.toHexString(intValue) + " ");
}
return buffer.toString();
}
public static void main(String[] args)
{
String s = "abcd";
System.out.println(s);
System.out.println(HexString.stringToHex(s));
}
}

Related

How do you print the highest and smallest number of ASCII value in string java

I found it, thank u mate. I actually too confuse yesterday, till i forget everything that i learnt. So here is my code, what do you think?
I just don't know why my minChar not working when i delete this code :
if(stringValue.charAt(i) != 32){
public class MyString {
public static void main(String[] args) {
String stringValue = "Hello World";
SearchMyString str = new SearchMyString(stringValue);
str.stringInfo();
}
}
class SearchMyString{
private char maxChar;
private char minChar;
String stringValue;
int ascii;
public SearchMyString(String stringValue){
this.stringValue = stringValue;
}
char getMinChar(String stringValue, int n){
minChar = 'z';
for(int i = 0;i<n-1;i++){
if(stringValue.charAt(i)<minChar){
if(stringValue.charAt(i) != 32){
minChar = stringValue.charAt(i);
ascii = (int)stringValue.charAt(i);
}
}
}
return minChar;
}
public void stringInfo(){
int size = stringValue.length();
System.out.println("Smallest char : "+getMinChar(stringValue,size) + "\tASCII : " + ascii);
}
}
Use this method:
public static char getMaxChar(String a){
char max = a.charAt(0);
for (int i=0; i<a.length(); i++){
if ((a.charAt(i) > max)){
max = a.charAt(i);
}
}
return max;
}
Test case:
ACBDEFG
Returns
G
So what did we change?
For starters, if we are trying to get the character in the String that has the highest char int value, we don't need n. We are looping through the String, so all we need is the length, which can already be supplied by the .length() method.
To call the method, just do:
SearchMyString search = new SearchMyString();
search.getMaxChar(nama);
EDIT: So to make the method more reliable, instead of automatically setting max to 'A', we can set it to the first char of a (e.g, a.charAt(0))

Replace while loop with lambda

I'm learning lambdas and I have an exercise to rewrite the while loop in this code using lambdas. This method gets encoded user input and returns decoded. I faced this problem and can't understand what I'm supposed to do. (I know that it's not hard, but I just can't get the concept.) I didn't find any similar questions here.
p.s. Also, one more qustion - can this while loop( or maybe whole method) be reworked with method reference?
public String decode(String input) {
StringBuilder letters = new StringBuilder();
input = input.toUpperCase();
int i = 0, j = 0;
while (i < input.length()) {
char symbol = input.charAt(i);
char keySymbol = KEY.charAt(j);
int newIndex = (ALPHABET.indexOf(symbol) - ALPHABET.indexOf(keySymbol)) % ALPHABET.length();
char newSymbol = ALPHABET.charAt(newIndex);
letters.append(newSymbol);
j = ++j % KEY.length();
i++;
}
return letters.toString().toLowerCase();
}
The code sample below includes the original decode method, and a new decodeLamda method.
The decodeLambda method replaces the iteration over 'input'. Running the sample will show they both have the same output. It is possible to change the loop to a method reference.
public class Main {
public static void main(String[] args) {
Main main = new Main();
System.out.println(main.decode("SECRET MESSAGE"));
System.out.println(main.decodeLambda("SECRET MESSAGE"));
}
public static String KEY = "HOPSCOTCH";
public static String ALPHABET = "ABCDEFGHIJKLMONOPQRSTUVWXYZ";
public String decode(String input) {
StringBuilder letters = new StringBuilder();
input = input.toUpperCase();
int i = 0, j = 0;
while (i < input.length()) {
char symbol = input.charAt(i);
char keySymbol = KEY.charAt(j);
int newIndex = Math.abs(ALPHABET.indexOf(symbol) - ALPHABET.indexOf(keySymbol)) % ALPHABET.length();
char newSymbol = ALPHABET.charAt(newIndex);
letters.append(newSymbol);
j = ++j % KEY.length();
i++;
}
return letters.toString().toLowerCase();
}
public String decodeLambda(String input) {
StringBuilder letters = new StringBuilder();
input = input.toUpperCase();
var ref = new Object() {
int j = 0;
};
input.chars()
.forEach( symbol -> {
char keySymbol = KEY.charAt(ref.j);
int newIndex = Math.abs(ALPHABET.indexOf(symbol) - ALPHABET.indexOf(keySymbol)) % ALPHABET.length();
char newSymbol = ALPHABET.charAt(newIndex);
letters.append(newSymbol);
ref.j = ++ref.j % KEY.length();
});
return letters.toString().toLowerCase();
}
}

Convert String to its Unicode code point

Assuming I have a string foo = "This is an apple"
The Unicode code point equivalent will be
" \\x74\\x68\\x69\\x73.......... \\x61\\x70\\x70\\x6c\\x65 "
T h i s ............. a p p l e
How do I convert from String foo
to
String " \\x74\\x68\\x69\\x73.......... \\x61\\x70\\x70\\x6c\\x65 "
try this..
public static String generateUnicode(String input) {
StringBuilder b = new StringBuilder(input.length());
for (char c : input.toCharArray()) {
b.append(String.format("\\u%04x", (int) c));
}
return b.toString();
}
Here a working code snippet to make the conversion:
public class HexTest {
public static void main(String[] args) {
String testStr = "hello日本語 ";
System.out.println(stringToUnicode3Representation(testStr));
}
private static String stringToUnicode3Representation(String str) {
StringBuilder result = new StringBuilder();
char[] charArr = str.toCharArray();
for (int i = 0; i < charArr.length; i++) {
result.append("\\u").append(Integer.toHexString(charArr[i] | 0x10000).substring(1));
}
return result.toString();
}
}
That display:
\u0068\u0065\u006c\u006c\u006f\u65e5\u672c\u8a9e\u0020
If you want to get rid of the extra zeros you elaborate it as described here.
Here another version to do the conversion, by passing "This is an apple" you get
\u54\u68\u69\u73\u20\u69\u73\u20\u61\u6e\u20\u61\u70\u70\u6c\u65
by using:
private static String str2UnicodeRepresentation(String str) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
int cp = Character.codePointAt(str, i);
int charCount = Character.charCount(cp);
//UTF characters may use more than 1 char to be represented
if (charCount == 2) {
i++;
}
result.append(String.format("\\u%x", cp));
}
return result.toString();
}

how to convert a string value to integer without using Integer.parseInt()?

I have this input like
String s = "6" , ss="99 , sss = "99999";
i need to store these values in an int reference variable ,
without using Integer.parseInt
any suggestion ? , no full code , just the hints ??
What about Scanner?
int a=new Scanner(s).nextInt();
Without util.
public static int parseInt(String s)
{
int ans=0;
for(int i=s.length()-1;i>=0;i--)
{
ans+=(s.charAt(i)-'0');
ans*=10;
}
return ans/10;
}
public class MyStringToNumber {
public static int convert_String_To_Number(String numStr){
char ch[] = numStr.toCharArray();
int sum = 0;
//get ascii value for zero
int zeroAscii = (int)'0';
for(char c:ch){
int tmpAscii = (int)c;
sum = (sum*10)+(tmpAscii-zeroAscii);
}
return sum;
}
public static void main(String a[]){
System.out.println("\"3256\" == "+convert_String_To_Number("3256"));
System.out.println("\"76289\" == "+convert_String_To_Number("76289"));
System.out.println("\"90087\" == "+convert_String_To_Number("90087"));
}
}
See more at this URL.
Try to get each char from the string and then the value of each char. 0 has a value of 48 so
char c = '9';
int i = c - 48;
Now i = 9. After that you only need to multiply this value with the appropriate power of 10 and add it to the total
public class ConvertIntoInt {
public static void main(String []args) {
String numStr = "3256";
char ch[] = numStr.toCharArray();
int sum = 0;
// Get ASCII value for zero
int zeroAscii = (int)'0';
for (char c:ch) {
int tmpAscii = (int)c;
System.out.println("Temp Ascii:" + tmpAscii);
sum = (sum * 10) + (tmpAscii - zeroAscii);
System.out.println(sum);
}
System.out.println(sum);
}
}

making a substring from string in java without using any string function

I was recently asked this question in an interview(3+ experience). No String function allowed including String.length. I was given 5 minutes to write the complete code.
Example
String ="abcfedbca"
subString = "fed"
Actually i asked him to elaborate a little more to which he said "it's easy java implementation what should i elaborate" and on basis of this question only he said my core java is very weak.
Note that you're question is not very precise and hence your requirements are not very clear.
Simple way :
String st = new StringBuilder(s).substring(3,6);
Or you can directly construct the new String using reflection to get the char array:
public static String substring(String s, int from, int to){
Field f = String.class.getDeclaredField("value");
f.setAccessible(true);
char [] tab = (char[])f.get(s);
f.setAccessible(false);
return new String(tab, from, to - from);
}
Those can also be options (note that it works only if the original String fits an hexadecimal format) :
String s ="abcfedbca";
BigInteger bi = new BigInteger(s, 16);
bi = bi.and(new BigInteger("16699392")); //0xfed000 in hexa
bi = bi.shiftRight(12);
System.out.println(bi.toString(16));
Or more simple :
String s ="abcfedbca";
System.out.println(Integer.toHexString((int)(Long.parseLong(s, 16) & 16699392) >> 12));
If you want a more general method, this one might suits your case :
public static void main(String [] args){
String s ="abcfedbca";
System.out.println(substring(s, 2, 5, 9));
}
public static String substring (String s, int from, int to, int length){
long shiftLeft = 0;
long shiftRight = (length - to - 1) * 4;
for(int i = 0; i < to - from - 1; i++){
shiftLeft += 15;
shiftLeft = shiftLeft << 4;
}
shiftLeft += 15;
return Long.toHexString((Long.parseLong(s, 16) & (shiftLeft << shiftRight)) >> shiftRight);
}
You can use a StringBuilder and call substring on it. Don't know whether that'd be allowed.
Here is the other way (although I am ashamed of this solution):
String str = "abcfedbca";
int from = 3, length = 3;
java.lang.reflect.Field valueField = String.class.getDeclaredField("value");
valueField.setAccessible(true);
char[] value = (char[]) valueField.get(str);
char[] sub = new char[length];
System.arraycopy(value, from, sub, 0, length);
String substring = new String(sub);
String buff = "abcfedbca";
System.out.println("substring is = " + buff.substring(3, 6));
how about this?
StringBuilder seems like a cheat to me since it's based on strings. I'd argue that you have to go down to byte primitives to meet the spirit of the test. Of course this calls getBytes which is technically a String function, so that breaks it also.
public static void main(String[] args) {
String full ="abcfedbca";
String desiredsubString = "fed";
byte[] fullByte = full.getBytes();
byte[] desiredByte = desiredsubString.getBytes();
byte[] foundStorage = new byte[desiredByte.length];
boolean foundStart = false;
int inserted = 0;
for (byte b : fullByte) {
if ( !foundStart && (b == desiredByte[0]) )
{
foundStorage[0] = b;
inserted++;
foundStart = true;
}
else if (foundStart && (inserted < foundStorage.length))
{
foundStorage[inserted] = b;
inserted++;
if ( inserted >= foundStorage.length )
{
break;
}
}
}
System.out.println("These should be equal: " + new String(desiredByte).equals(new String(foundStorage)));
}
Maybe:
String value = "abcfedbca";
BigInteger bi = new BigInteger(value, 16);
bi = bi.divide(BigInteger.TEN);
bi = bi.divide(BigInteger.TEN);
bi = bi.divide(BigInteger.TEN);
bi = bi.divide(BigInteger.TEN);
bi = bi.divide(BigInteger.TEN);
bi = bi.divide(BigInteger.TEN);
bi = bi.divide(BigInteger.TEN);
int val = bi.subtract(BigInteger.valueOf(535)).intValue();
String hex = Integer.toHexString(val);
System.out.println(hex);
Output: fed
How about using a JPasswordField to get the chars:
private static String substring(String str, int beginIndex, int endIndex) {
return new String(new JPasswordField(str).getPassword(), beginIndex, endIndex - beginIndex);
}
And the String constructor is not a String method, isn't it?
public String submethod(String data, int firstindex, int lastindex) {
char[] chars=data.toCharArray();
char[]charnew= new char [lastindex];
for(int i=firstindex; i< lastindex;i++) {
charnew[i]=chars[i];
}
return new String(charnew);
}

Categories

Resources