Java NumberFormat.getNumberInstance(Locale) inconsistent for negativePrefix - java

Trying to format negative number to String using:
(DecimalFormat) NumberFormat.getNumberInstance(new Locale("no")));
Using jdk-10.0.2. I have found out that Norway and some other countries are using Unicode Character 'MINUS SIGN' (U+2212) for negative prefix, while most other countries are using Unicode Character 'HYPHEN-MINUS' (U+002D). This is a problem as test are failing on equal and on my Mac all negative prefix is HYPHEN-MINUS.
A solution I have found is to call setNegativePrefix("-") after getting the DecimalFormat to override the strange local negative prefixes.
Please also see workaround at Orcale (end of page) https://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8214926.
#Test
public void norwegianNegativePrefixDifferentFromEnglish() throws UnsupportedEncodingException {
Assertions.assertThat(((DecimalFormat) NumberFormat.getNumberInstance(new Locale("no"))).getNegativePrefix())
.isEqualTo(((DecimalFormat) NumberFormat.getNumberInstance(new Locale("en"))).getNegativePrefix());
}
Anyone know why? Executing this Java gives the attached results:
public void fintLocals() {
HashMap<String, List<String>> negativeSignAndLocals = new HashMap<String, List<String>>();
for (Locale locale : Locale.getAvailableLocales()) {
DecimalFormat formatForLocal = ((DecimalFormat) NumberFormat.getNumberInstance(locale));
// System.out.println(formatForLocal.getNegativePrefix()+ " minus for "+locale);
List<String> negLoc = negativeSignAndLocals.get(formatForLocal.getNegativePrefix());
if (negLoc == null) {
negativeSignAndLocals.put(formatForLocal.getNegativePrefix(), new ArrayList<>());
}
negativeSignAndLocals.get(formatForLocal.getNegativePrefix()).add(locale.toString());
}
for (Map.Entry<String, List<String>> entry : negativeSignAndLocals.entrySet()) {
System.out.println("Negative sign = " + entry.getKey() + " as Hex value " + charToHex(entry.getKey().charAt(0))
+ " are used by: " + (String) String.join(",", entry.getValue()));
}
}
static public String byteToHex(byte b) {
// Returns hex String representation of byte b
char hexDigit[] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
char[] array = {hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f]};
return new String(array);
}
static public String charToHex(char c) {
// Returns hex String representation of char c
byte hi = (byte) (c >>> 8);
byte lo = (byte) (c & 0xff);
return byteToHex(hi) + byteToHex(lo);
}
Negative sign − as Hex value 2212 are used by: nn,sv_SE,sv,se_NO,nb_SJ,no_NO_NY,sv_FI,no,ksh,gsw_CH,et,gsw,gsw_FR,fi,et_EE,rm,nb_NO,fi_FI,rm_CH,ksh_DE,se_FI,no_NO,lt_LT,nn_NO,se_SE,se,fo_DK,fo_FO,fo,lt,gsw_LI,sv_AX,nb
Negative sign - as Hex value 002d are used by: ,bg,kea,zu,am_ET,fr_DZ,ti_ET,bo_CN,hsb,qu_EC,ta_SG,lv,en_NU,zh_SG_#Hans,en_MS,en_GG,en_JM,vo,kkj,sr_ME,es_BO,dz_BT,mer,sah,en_ZM,fr_ML,br,ha_NG,bs_BA,dsb_DE,sk,os_GE,ml,en_MT,en_LR,en_GH,en_IL,cs,el,tzm_MA,af,sw_UG,ses_ML,smn,tk_TM,sr_ME_#Cyrl,dsb,lkt_US,vai_LR_#Latn,ji_001,yo_NG,khq,sw_CD,vo_001,en_PW,pl_PL,fil_PH,sr_CS,ne_IN,es_PH,es_ES,es_CO,bg_BG,ji,bs_BA_#Latn,en_VC,es_US,agq,hsb_DE,en_US_POSIX,en_150,en_KN,ha_NE,pt_MO,ebu,ro_RO,zh__#Hans,lb_LU,sr_ME_#Latn,es_GT,so_KE,dje_NE,bas_CM,fr_PM,fr_MG,es_CL,mn,agq_CM,kam_KE,teo,tr_TR,eu,en_MO,shi__#Tfng,en_BZ,sq_AL,es_DO,ru,twq_NE,az,nmg_CM,kl_GL,en_NR,nd,kk,az__#Cyrl,en_MP,en_GD,tk,hy,shi__#Latn,en_BW,en_AU,en_CY,kab_DZ,kde_TZ,ta_MY,ti_ER,nus_SS,en_RW,nd_ZW,ksb,luo,lb,ne,en_IE,zh_SG,ln_CD,en_KI,nnh_CM,om_ET,ja_JP,my,ka,mgh,or_IN,fr_MF,shi,kl,yue_HK,en_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,pt_ST,ak_GH,fur_IT,ta_IN,en_SE,fr_GF,lkt,zh_CN_#Hans,is,es_419,si,pt_AO,en_001,en,guz_KE,es_IC,ca,ru_KG,fr_MR,zh_TW_#Hant,bm_ML,pa_PK,kw_GB,ug_CN,as_IN,es_BR,zh_HK,khq_ML,sw_KE,en_SB,th_TH,rw_RW,chr_US,shi_MA_#Tfng,nyn,yue,jmc,en_MW,naq_NA,mk,en_IO,en_DE,en_CC,bs,ro_MD,en_FI,pt_PT,fy,az_AZ_#Cyrl,th,dav_KE,uz_UZ,shi_MA_#Latn,es_CU,en_SC,en_VI,haw,eu_ES,en_UG,en_NZ,dje,es_UY,bas,mas_KE,ru_UA,sg_CF,el_GR,yav_CM,uz__#Latn,sg,da_GL,en_FJ,de_LI,en_BB,km_KH,smn_FI,hr_BA,de_AT,nl,lu_CD,ca_ES_VALENCIA,so_SO,lv_LV,es_CR,fr_GA,sr,sr_RS_#Cyrl,bem,en_MU,da,wae,gl_ES,en_IM,az_AZ_#Latn,en_LS,ig,en_HK,en_GI,ce_RU,en_CA,gd,ka_GE,fr_SY,sw_TZ,fr_RW,so_ET,nl_BE,mg_MG,cy_GB,en_VG,cu,os_RU,sr_RS_#Latn,en_TC,ky_KG,af_NA,vun,en_IN,lu,ki,yo,es_NI,ff_MR,mas_TZ,ti,kok,ewo,ms_BN,br_FR
Negative sign ‎ as Hex value 200e are used by: fa_AF,ar_EH,fa_IR,ar_MR,fa,ur_IN,ps,lrc_IR,lrc_IQ,ps_AF,ar_DZ,iw,lrc,pa_PK_#Arab,ar_MA,iw_IL,ur,uz__#Arab,ar_LB,ks_IN,ur_PK,mzn,mzn_IR,uz_AF_#Arab,ar_TN,ks,pa__#Arab,ar_LY
Negative sign ‏ as Hex value 200f are used by: ar_JO,ar_SA,ar_TD,ar_EG,ar_SD,ar_KM,ar_IL,ar_SY,ar_PS,ar_YE,ar_OM,ar_SS,ar_ER,ar_SO,ar_AE,ar_BH,ar_IQ,ar_QA,ckb_IQ,ar,ckb_IR,ar_001,ckb,ar_KW,ar_DJ

Related

How to convert Hex to decimal value in Java

I currently have an application where I receive 2 values e.g. 0e 15 through bluetooth.
I now want to display these in decimal values.
The code is as follows:
private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
public static String formatHexString(byte[] data) {
return formatHexString(data, false);
}
public static String formatHexString(byte[] data, boolean addSpace) {
if (data == null || data.length < 1)
return null;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.length; i++) {
String hex = Integer.toHexString(data[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex);
if (addSpace)
sb.append(" ");
}
return sb.toString().trim();
}
}
How would I go about into converting this string so I can decimal values back?
You can use java.lang.Integer library's method parseInt.
simply do Integer.parseInt(hexString,16);
For more information you can refer to documentation here.
I was confused as I somehow thought bytes had to be displayed in hexadecimal value. It didn't cross my mind that I could just showcase two bytes in decimal value. Currently have what I want with the following code:
public class HexUtil {
public static String formatDecimalString(byte[] data, boolean addSpace) {
if (data == null || data.length < 1)
return null;
int negative = data[0] < 0 ? -1 : 1;
BigInteger bigInteger = new BigInteger(negative, data);
String decimal = bigInteger.toString();
if(addSpace) {
decimal = decimal.replaceAll("(.{2})", "$1 ");
}
return decimal;
}
}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -65

i am trying to solve this question
https://www.hackerrank.com/challenges/pangrams
and here's my code
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Pangram {
public static String alltrim(String s)
{ String s1="";
int i,j,k=0;
for(i=0;i<s.length();i++)
{
char ch=s.charAt(i);
if(ch!=' ')
break;
}
for(j=s.length()-1;j>=0;j--)
{
char ch=s.charAt(j);
if(ch!=' ')
break;
}
for(k=i;k<j+1;k++)
s1 = s1 + s.charAt(k);
return s1;
}
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
String input = reader.nextLine();String s,s1;
s = input.toLowerCase();
s1 = alltrim(s);
if( check(s1) )
System.out.println("pangram");
else
System.out.println("not pangram");
}
public static boolean check(String input)
{
int [] count = new int[26];
for( int i = 0; i < input.length(); i++ )
{
char ch = input.charAt(i);
count[ch-'a']++;
}
for( int cnt:count )
{
if( cnt ==0 )
return false;
}
return true;
}
}
i always get this error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -65
at Pangram.check(Pangram.java:46)
at Pangram.main(Pangram.java:35)
i am trying to find out where the problem is but i coudn't ... can anyone help me?
Here's one way
public static void main(final String[] args) throws IOException {
Scanner reader = new Scanner(System.in);
String line = reader.nextLine();
// Verify input argument length.
final char[] allCharacters = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
final TreeSet<Character> charactersPresent = new TreeSet<Character>();
// Parse the line into letters.
final char[] letters = line.toLowerCase().toCharArray();
// Keep a set of those that are present.
for (final char letter : letters) {
charactersPresent.add(letter);
}
// Print the letters present in the alphabet but not in the input.
final StringBuilder missingLettersBuilder = new StringBuilder();
for (final char character : allCharacters) {
if (!charactersPresent.contains(character)) {
missingLettersBuilder.append(character);
}
}
if (missingLettersBuilder.length() == 0) {
System.out.println("This is a PANGRAM");
} else {
System.out.println("Not a PANGRAM because it doesn't have "+missingLettersBuilder.toString());
}
}
The problem is in
count[ch-'a']++;
where ch is 6(as you entered) and you are subtracting '6'-'1' so its generating a value by subtracting the ASCII values and give
count[-43]++;
The java.lang.ArrayIndexOutOfBoundsException: -65 happen because you subtract a(97) to a space character which is represented by 32 in the ASCII table (32-97=-65).
Which mean that the problem is in your allTrim method which does not replace all spaces as you probably expected.
If you want to replace all spaces of your string, you can use the replaceAll method of String.
Discard the s1 = alltrim(s); line and replace it by s1 = s.replaceAll(" ", "");.
Now entering the input you gave me in comments
aaabbb ab abc mnop xyyx xaxbbbxx
Won't give any exception.
As for the other exception you had (out of bound -43), it is simply because you entered
6 aaabbb ab abc mnop xyyx xaxbbbxx
6 is represented by 54 in the ASCII table, 54-97 = 43. Looking at the requirement on the link you gave us, you should only compare alphabetical letter so I suppose this is a mistake.
Note that you can easily remove all number of a String, your replace line would become :
s1 = s.replaceAll(" ", "").replaceAll("\\d", "");
Now it would not give any error even when entering
6 aaabbb ab abc mnop xyyx xaxbbbxx

Trying to write a decryption function in Java

I'm finished with the plugin finally, and started working on another project. That project is a simple bit of software to encrypt a string given an encryption key and the string itself. So I wrote that, and it seems to be working fine, but I can't figure out how to decrypt it. I used to have an array with the encrypted alphabet, but I figured out a way to do without that in the encryption function and there should be a way to do without it in the decryption as well.
My encryption function:
public static String e(String toEncrypt, int encKey) {
encKey %= ALPHABET.length;
toEncrypt = toEncrypt.toLowerCase();
char[] TEChar = toEncrypt.toCharArray();
for (int i = 0; i < toEncrypt.length(); i++) {
for (int j = 0; j < ALPHABET.length; j++) {
if (TEChar[i] == '`') {
TEChar[i] = '_';
}
else if (TEChar[i] == ALPHABET[j]) {
TEChar[i] = ALPHABET[(j + encKey) % ALPHABET.length];
break;
}
}
}
toEncrypt = String.valueOf(TEChar) + "`" + encKey;
return toEncrypt;
}
ALPHABET (the array, and I realize that it contains more than just the alphabet.):
char[] ALPHABET = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' ', '1',
'2', '3', '4', '5', '6', '7', '8', '9', '0', ',', '.', ';', ':', '[', ']', '{',
'}', '?'};
Rather than making a new array just to have the offset characters, I did that with a simple addition and use of the remainder operator. I tried using subtraction and the same thing, but it didn't work as I would need it to wrap around to 26. Somehow I get the feeling that something glaringly obvious is the solution.
Try this:
public static String e(String toEncrypt, int encKey, boolean addEncKey) {
encKey %= ALPHABET.length;
toEncrypt = toEncrypt.toLowerCase();
char[] TEChar = toEncrypt.toCharArray();
for (int i = 0; i < toEncrypt.length(); i++) {
for (int j = 0; j < ALPHABET.length; j++) {
if (TEChar[i] == '`') {
TEChar[i] = '_';
} else if (TEChar[i] == ALPHABET[j]) {
TEChar[i] = ALPHABET[(j + encKey + ALPHABET.length)
% ALPHABET.length];
break;
}
}
}
if (addEncKey) {
toEncrypt = String.valueOf(TEChar) + "`" + encKey;
} else {
toEncrypt = String.valueOf(TEChar);
}
return toEncrypt;
}
This how I tested it:
public static void main(String[] args) {
String encoded = e("ABDSDfz}", 2, true);
System.out.println(encoded);
String decoded = e(
encoded.substring(0, encoded.indexOf("`")),
-Integer.parseInt(encoded.substring(encoded.indexOf("`") + 1)),
false);
System.out.println(decoded);
}
As you can see I moved some logic to method invocation (you can easily write a decryption function that wrapes around encryption like this:
public static String decrypt(String encoded) {
return e(encoded.substring(0, encoded.indexOf("`")),
-Integer.parseInt(encoded.substring(encoded.indexOf("`") + 1)),
false);
}
The decrypion and encryption works basically in the same way but decryption uses opposite encKey (for example instead of 22 it will use -22), this done in invocation. You add encKey after '`' sign - I didn't wanted that in decoded message so I cut it out when parsing encoded string to method and added booleam parameter addEncKey so I can disable adding addEncKey.
I also changed in the code this line:
TEChar[i] = ALPHABET[(j + encKey + ALPHABET.length)
% ALPHABET.length];
This is an easy way to deal with negative indexes that can happen when encKey is negative.

Decimal to Hexadecimal Converter in Java

I have a homework assignment where I need to do three-way conversion between decimal, binary and hexadecimal. The function I need help with is converting a decimal into a hexadecimal. I have nearly no understanding of hexadecimal, nonetheless how to convert a decimal into hex. I need a function that takes in an int dec and returns a String hex. Unfortunately I don't have any draft of this function, I'm completely lost. All I have is this.
public static String decToHex(int dec)
{
String hex = "";
return hex;
}
Also I can't use those premade functions like Integer.toHexString() or anything, I need to actually make the algorithm or I wouldn't have learned anything.
One possible solution:
import java.lang.StringBuilder;
class Test {
private static final int sizeOfIntInHalfBytes = 8;
private static final int numberOfBitsInAHalfByte = 4;
private static final int halfByte = 0x0F;
private static final char[] hexDigits = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
public static String decToHex(int dec) {
StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes);
hexBuilder.setLength(sizeOfIntInHalfBytes);
for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i)
{
int j = dec & halfByte;
hexBuilder.setCharAt(i, hexDigits[j]);
dec >>= numberOfBitsInAHalfByte;
}
return hexBuilder.toString();
}
public static void main(String[] args) {
int dec = 305445566;
String hex = decToHex(dec);
System.out.println(hex);
}
}
Output:
1234BABE
Anyway, there is a library method for this:
String hex = Integer.toHexString(dec);
Simple:
public static String decToHex(int dec)
{
return Integer.toHexString(dec);
}
As mentioned here: Java Convert integer to hex integer
I need a function that takes in an int dec and returns a String hex.
I found a more elegant solution from
http://introcs.cs.princeton.edu/java/31datatype/Hex2Decimal.java.html . I changed a bit from the original ( see the edit )
// precondition: d is a nonnegative integer
public static String decimal2hex(int d) {
String digits = "0123456789ABCDEF";
if (d <= 0) return "0";
int base = 16; // flexible to change in any base under 16
String hex = "";
while (d > 0) {
int digit = d % base; // rightmost digit
hex = digits.charAt(digit) + hex; // string concatenation
d = d / base;
}
return hex;
}
Disclaimer: I ask this question in my coding interview. I hope this solution doesn't get too popular :)
Edit June 17 2016 : I added the base variable to give the flexibility to change into any base : binary, octal, base of 7 ...
According to the comments, this solution is the most elegant so I removed the implementation of Integer.toHexString() .
Edit September 4 2015 : I found a more elegant solution http://introcs.cs.princeton.edu/java/31datatype/Hex2Decimal.java.html
Consider dec2m method below for conversion from dec to hex, oct or bin.
Sample output is
28 dec == 11100 bin
28 dec == 34 oct
28 dec == 1C hex
public class Conversion {
public static void main(String[] argv) {
int x = 28; // sample number
if (argv.length > 0)
x = Integer.parseInt(argv[0]); // number from command line
System.out.printf("%d dec == %s bin\n", i, dec2m(x, 2));
System.out.printf("%d dec == %s oct\n", i, dec2m(x, 8));
System.out.printf("%d dec == %s hex\n", i, dec2m(x, 16));
}
static String dec2m(int N, int m) {
String s = "";
for (int n = N; n > 0; n /= m) {
int r = n % m;
s = r < 10 ? r + s : (char) ('A' - 10 + r) + s;
}
return s;
}
}
Here is the code for any number :
import java.math.BigInteger;
public class Testing {
/**
* #param args
*/
static String arr[] ={"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
public static void main(String[] args) {
String value = "214";
System.out.println(value + " : " + getHex(value));
}
public static String getHex(String value) {
String output= "";
try {
Integer.parseInt(value);
Integer number = new Integer(value);
while(number >= 16){
output = arr[number%16] + output;
number = number/16;
}
output = arr[number]+output;
} catch (Exception e) {
BigInteger number = null;
try{
number = new BigInteger(value);
}catch (Exception e1) {
return "Not a valid numebr";
}
BigInteger hex = new BigInteger("16");
BigInteger[] val = {};
while(number.compareTo(hex) == 1 || number.compareTo(hex) == 0){
val = number.divideAndRemainder(hex);
output = arr[val[1].intValue()] + output;
number = val[0];
}
output = arr[number.intValue()] + output;
}
return output;
}
}
Another possible solution:
public String DecToHex(int dec){
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F'};
String hex = "";
while (dec != 0) {
int rem = dec % 16;
hex = hexDigits[rem] + hex;
dec = dec / 16;
}
return hex;
}
The easiest way to do this is:
String hexadecimalString = String.format("%x", integerValue);
I will use
Long a = Long.parseLong(cadenaFinal, 16 );
since there is some hex that can be larguer than intenger and it will throw an exception
Code to convert DECIMAL -to-> BINARY, OCTAL, HEXADECIMAL
public class ConvertBase10ToBaseX {
enum Base {
/**
* Integer is represented in 32 bit in 32/64 bit machine.
* There we can split this integer no of bits into multiples of 1,2,4,8,16 bits
*/
BASE2(1,1,32), BASE4(3,2,16), BASE8(7,3,11)/* OCTAL*/, /*BASE10(3,2),*/
BASE16(15, 4, 8){
public String getFormattedValue(int val){
switch(val) {
case 10:
return "A";
case 11:
return "B";
case 12:
return "C";
case 13:
return "D";
case 14:
return "E";
case 15:
return "F";
default:
return "" + val;
}
}
}, /*BASE32(31,5,1),*/ BASE256(255, 8, 4), /*BASE512(511,9),*/ Base65536(65535, 16, 2);
private int LEVEL_0_MASK;
private int LEVEL_1_ROTATION;
private int MAX_ROTATION;
Base(int levelZeroMask, int levelOneRotation, int maxPossibleRotation) {
this.LEVEL_0_MASK = levelZeroMask;
this.LEVEL_1_ROTATION = levelOneRotation;
this.MAX_ROTATION = maxPossibleRotation;
}
int getLevelZeroMask(){
return LEVEL_0_MASK;
}
int getLevelOneRotation(){
return LEVEL_1_ROTATION;
}
int getMaxRotation(){
return MAX_ROTATION;
}
String getFormattedValue(int val){
return "" + val;
}
}
public void getBaseXValueOn(Base base, int on) {
forwardPrint(base, on);
}
private void forwardPrint(Base base, int on) {
int rotation = base.getLevelOneRotation();
int mask = base.getLevelZeroMask();
int maxRotation = base.getMaxRotation();
boolean valueFound = false;
for(int level = maxRotation; level >= 2; level--) {
int rotation1 = (level-1) * rotation;
int mask1 = mask << rotation1 ;
if((on & mask1) > 0 ) {
valueFound = true;
}
if(valueFound)
System.out.print(base.getFormattedValue((on & mask1) >>> rotation1));
}
System.out.println(base.getFormattedValue((on & mask)));
}
public int getBaseXValueOnAtLevel(Base base, int on, int level) {
if(level > base.getMaxRotation() || level < 1) {
return 0; //INVALID Input
}
int rotation = base.getLevelOneRotation();
int mask = base.getLevelZeroMask();
if(level > 1) {
rotation = (level-1) * rotation;
mask = mask << rotation;
} else {
rotation = 0;
}
return (on & mask) >>> rotation;
}
public static void main(String[] args) {
ConvertBase10ToBaseX obj = new ConvertBase10ToBaseX();
obj.getBaseXValueOn(Base.BASE16,12456);
// obj.getBaseXValueOn(Base.BASE16,300);
// obj.getBaseXValueOn(Base.BASE16,7);
// obj.getBaseXValueOn(Base.BASE16,7);
obj.getBaseXValueOn(Base.BASE2,12456);
obj.getBaseXValueOn(Base.BASE8,12456);
obj.getBaseXValueOn(Base.BASE2,8);
obj.getBaseXValueOn(Base.BASE2,9);
obj.getBaseXValueOn(Base.BASE2,10);
obj.getBaseXValueOn(Base.BASE2,11);
obj.getBaseXValueOn(Base.BASE2,12);
obj.getBaseXValueOn(Base.BASE2,13);
obj.getBaseXValueOn(Base.BASE2,14);
obj.getBaseXValueOn(Base.BASE2,15);
obj.getBaseXValueOn(Base.BASE2,16);
obj.getBaseXValueOn(Base.BASE2,17);
System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE2, 4, 1));
System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE2, 4, 2));
System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE2, 4, 3));
System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE2, 4, 4));
System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE16,15, 1));
System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE16,30, 2));
System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE16,7, 1));
System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE16,7, 2));
System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE256, 511, 1));
System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE256, 511, 2));
System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE256, 512, 1));
System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE256, 512, 2));
System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE256, 513, 2));
}
}
Here's mine
public static String dec2Hex(int num)
{
String hex = "";
while (num != 0)
{
if (num % 16 < 10)
hex = Integer.toString(num % 16) + hex;
else
hex = (char)((num % 16)+55) + hex;
num = num / 16;
}
return hex;
}
A better solution to convert Decimal To HexaDecimal and this one is less complex
import java.util.Scanner;
public class DecimalToHexa
{
public static void main(String ar[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a Decimal number: ");
int n=sc.nextInt();
if(n<0)
{
System.out.println("Enter a positive integer");
return;
}
int i=0,d=0;
String hx="",h="";
while(n>0)
{
d=n%16;`enter code here`
n/=16;
if(d==10)h="A";
else if(d==11)h="B";
else if(d==12)h="C";
else if(d==13)h="D";
else if(d==14)h="E";
else if(d==15)h="F";
else h=""+d;
hx=""+h+hx;
}
System.out.println("Equivalent HEXA: "+hx);
}
}
The following converts decimal to Hexa Decimal with
Time Complexity : O(n) Linear Time with out any java inbuilt function
private static String decimalToHexaDecimal(int N) {
char hexaDecimals[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
StringBuilder builder = new StringBuilder();
int base= 16;
while (N != 0) {
int reminder = N % base;
builder.append(hexaDecimals[reminder]);
N = N / base;
}
return builder.reverse().toString();
}

convert each item of a char[] to its ASCII code

How can I convert each item of a char[] (char array) to its ascii code? char_arr[i].charAt(0) doesn't work as the method doesn't exist. I can't use the toString method for char_arr[i].
import java.util.Scanner;
/**
* Created by mona on 2/25/16.
*/
public class FunnyString {
public static void main(String[] args){
Scanner sc= new Scanner(System.in);
int num_str;
num_str=sc.nextInt();
Boolean flag=true;
for (int i=0;i<num_str;i++){
StringBuilder strb = new StringBuilder(scan.nextLine());
StringBuilder str_reverse=strb.reverse();
Char[] strb_arr=strb.toString().toCharArray();
Char[] strb_rev_arr=str_reverse.toString().toCharArray();
for (int i=1; i<strb_arr.length;i++){
if (Math.abs(strb_arr[i]-strb_arr[i-1])!=Math.abs(strb_rev_arr[i]-strb_rev_arr[i-1])){
flag=false;
}
}
}
if (flag==false){
System.out.println("Not funny");
}
else{
System.out.println("Funny");
}
}
}
You can try this: cast it to int
char[] chars;
for (char aChar : chars) {
System.out.println("chars = " + (int) aChar);
}
Traverse through the array, assigning each char value to an int by casting, i.e.,
char_to_ascii[i] = (int) char_arr[i] ;
You can use casting to integer (int) , or just add 0 to your char.
See this
char[] cs = {'a', 'b', 'c'};
for (Character c : cs)
{
System.out.println(c + 0);
}
Output
97
98
99
See it's ascii codes of given chars http://www.asciitable.com/ .
Additionally you could get a char from a numeric value.
char[] cs = {'a', 'b', 'c'};
for (Character c : cs)
{
System.out.println(c + 0);
System.out.println( (char)(c + 0) );
}
Output
97
a
98
b
99
c
Because elements of char[] are UTF-16 code units, the standard numerical representation is in the form of backslash, "u", four hexadecimal digits. For example, 'a' is represented as '\u0061'.
Also, note that some Unicode codepoints are encoded in two UTF-16 code units. For example, the musical quarter note "𝅘𝅥" (might not display with the font your browser is using with this web page).
for (char c : "abc𝅘𝅥123".toCharArray())
{
System.out.println(String.format("\\u%04X", (int)c));
}

Categories