Conversion from ASCII values to Char - java

String source = "WEDGEZ"
char letter = source.charAt(i);
shift=5;
for (int i=0;i<source.length();i++){
if (source.charAt(i) >=65 && source.charAt(i) <=90 )
letterMix =(char)(('D' + (letter - 'D' + shift) % 26));
}
Ok what I'm trying to do is take the string WEDGEZ, and shift each letter by 5, so W becomes B and E becomes J, etc. However I feel like there is some inconsistency with the numbers I'm using.
For the if statement, I'm using ASCII values, and for the
letterMix= statement, I'm using the numbers from 1-26 (I think). Well actually, the question is about that too:
What does
(char)(('D' + (letter - 'D' + shift) % 26)); return anyway? It returns a char right, but converted from an int. I found that statement online somewhere I didn't compose it entirely myself so what exactly does that statement return.
The general problem with this code is that for W it returns '/' and for Z it returns _, which I'm guessing means it's using the ASCII values. I really dont know how to approach this.
Edit: New code
for (int i=0;i<source.length();i++)
{
char letter = source.charAt(i);
letterMix=source.charAt(i);
if (source.charAt(i) >=65 && source.charAt(i) <=90 ){
letterMix=(char)('A' + ( ( (letter - 'A') + input ) % 26));
}
}

Well I'm not sure if this homework, so i'll be stingy with the Code.
You're Writing a Caesar Cipher with a shift of 5.
To address your Z -> _ problem...I'm Assuming you want all the letters to be changed into encoded letters (and not weird Symbols). The problem is ASCII values of A-Z lie between 65 and 90.
When coding Z (for eg), you end up adding 5 to it, which gives u the value 95 (_).
What you need to do is Wrap around the available alphabets. First isolate, the relative position of the character in the alphabets (ie A = 0, B = 1 ...) You Need to subtract 65 (which is ASCII of A. Add your Shift and then apply modulus 26. This will cause your value to wrap around.
eg, it your encoding Z, (ASCII=90), so relative position is 25 (= 90 - 65).
now, 25 + 5 = 30, but you need the value to be within 26. so you take modulus 26
so 30 % 26 is 4 which is E.
So here it is
char letter = message(i);
int relativePosition = letter - 'A'; // 0-25
int encode = (relativePosition + shift) % 26
char encodedChar = encode + 'A' // convert it back to ASCII.
So in one line,
char encodedChar = 'A' + ( ( (letter - 'A') + shift ) % 26)
Note, This will work only for upper case, if your planning to use lower case, you'll need some extra processing.
You can use Character.isUpperCase() to check for upper case.

You can try this code for convert ASCII values to Char
class Ascii {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
char ch=sc.next().charAt(0);
if(ch==' ') {
int in=ch;
System.out.println(in);
}
}
}

Related

Get the Unicode from a Hexadecimal

I've been searching for a solution to my problem for days but can't get a spot-on answer when looking at previously answered questions/ blogs / tutorials etc. all over the internet.
My aim is to write a program which takes a decimal number as an input and then calculates the hexadecimal number and also prints the unicode-symbol of said hexadecimal number (\uXXXX).
My problem is I can't "convert" the hexadecimal number to unicode. (It has to be written in this format: \uXXXX)
Example:
Input:
122 (= Decimal)
Output:
Hexadecimal: 7A
Unicode: \u007A | Unicode Symbol: Latin small letter "z"
The only thing I've managed to do is print the unicode (\u007A), but I want the symbol ("z").
I thought if the unicode only has 4 numbers/letters, I would just need to "copy" the hexadecimal into the code and fill up the remaining places with 0's and it kinda worked, but as I said I need the symbol not the code. So I tried and tried, but I just couldn't get the symbol.
By my understanding, if you want the symbol you need to print it as a string.
But when trying it with a string I get the error "illegal unicode escape".
It's like you only can print pre-determined unicodes and not "random" ones generated on the spot in relation of your input.
I'm only a couple days into Java, so apologies if I have missed anything.
Thank you for reading.
My code:
int dec;
int quotient;
int rest;
int[]hex = new int[10];
char[]chars = new char[]{
'F',
'E',
'D',
'C',
'B',
'A'
};
String unicode;
// Input Number
System.out.println("Input decimal number:");
Scanner input = new Scanner(System.in);
dec = input.nextInt();
//
// "Converting to hexadecimal
quotient = dec / 16;
rest = dec % 16;
hex[0] = rest;
int j = 1;
while (quotient != 0) {
rest = quotient % 16;
quotient = quotient / 16;
hex[j] = rest;
j++;
}
//
/*if (j == 1) {
unicode = '\u000';
}
if (j == 2) {
unicode = '\u00';
}
if (j == 3) {
unicode = '\u0';
}*/
System.out.println("Your number: " + dec);
System.out.print("The corresponding Hexadecimal number: ");
for (int i = j - 1; i >= 0; i--) {
if (hex[i] > 9) {
if (j == 1) {
unicode = "\u000" + String.valueOf(chars[16 - hex[i] - 1]);
}
if (j == 2) {
unicode = "\u00" + String.valueOf(chars[16 - hex[i] - 1]);
}
if (j == 3) {
unicode = "\u0" + String.valueOf(chars[16 - hex[i] - 1]);
}
System.out.print(chars[16 - hex[i] - 1]);
} else {
if (j == 1) {
unicode = "\u000" + Character.valueOf[hex[i]);
}
if (j == 2) {
unicode = "\u00" + Character.valueOf(hex[i]);
}
if (j == 3) {
unicode = "\u0" + Character.valueOf(hex[i]);
}
System.out.print(hex[i]);
}
}
System.out.println();
System.out.print("Unicode: " + (unicode));
}
It's not an advanced code whatsoever, I wrote it exactly how I would calculate it on paper.
Dividing the number through 16 until I get a 0 and what remains while doing so is the hexadecimal equivalent.
So I put it in a while loop, since I would divide the number n-times until I got 0, the condition would be to repeat the division until the quotient equals zero.
While doing so the remains of each division would be the numbers/letters of my hexadecimal number, so I need them to be saved. I choose an integer array to do so. Rest (remains) = hex[j].
I also threw a variable in the called "j", so I would now how many times the division was repeated. So I could determine how long the hexadecimal is.
In the example it would 2 letters/numbers long (7A), so j = 2.
The variable would then be used to determine how many 0's I would need to fill up the unicode with.
If I have only 2 letters/numbers, it means there are 2 empty spots after \u, so we add two zeros, to get \u007A instead of \u7A.
Also the next if-command replaces any numbers higher than 9 with a character from the char array above. Basically just like you would do on paper.
I'm very sorry for this insanely long question.
U+007A is the 3 bytes int code pointer.
\u007A is the UTF-16 char.
A Unicode code pointer, symbol, sometimes is converted to two chars and then the hexadecimal numbers do not agree. Using code pointers hence is best. As UTF-16 is just an encoding scheme for two-bytes representation, where the surrogate pairs for 3 byte Unicode numbers do not contain / or such (high bit always 1).
int hex = 0x7A;
hex = Integer.parseUnsignedInt("007A", 16);
char ch = (char) hex;
String stringWith1CodePoint = new String(new int[] { hex }, 0, 1);
int[] codePoints = stringWith1CodePoint.codePoints().toArray();
String s = "𝄞"; // U+1D11E = "\uD834\uDD1E"
You can simply use System.out.printf or String.format to do what you want.
Example:
int decimal = 122;
System.out.printf("Hexadecimal: %X\n", decimal);
System.out.printf("Unicode: u%04X\n", decimal);
System.out.printf("Latin small letter: %c\n", (char)decimal);
Output:
Hexadecimal: 7A
Unicode: u007A
Latin small letter: z

How to shift characters in an array left in Java? [duplicate]

This question already has answers here:
How do I shift array characters to the right in Java?
(2 answers)
Closed 5 years ago.
This is what I have right now:
class encoded{
public static void main(String[] args){
int shift = In.getInt();
String s1 = "bool";
char[] ch=s1.toCharArray();
for(int i=0;i<ch.length;i++){
char c = (char) (((ch[i] - 'a' - shift) % 26) + 'a');
System.out.print(c);
}
}
}
This code works to shift all characters in the string left by however much I want it to shift. The problem arises when, for example, I shift 'abc' 1 left, it returns '`ab'. What I want is for the characters to wrap back around to 'z' instead, so that the shifted 'abc' becomes 'zab' instead. How would I go about doing this? The characters need to always wrap back around to z when they're shifted left of 'a', and need to wrap back around to a when they're shifted right of 'z' (this would be done by changing "'a' - shift" to "'a' + shift".
Thanks so much in advance!
Not doing your homework for you, but giving you some hints:
char c = (char) (((ch[i] - 'a' - shift) % 26) + 'a');
You see, you are doing the shift operation unconditionally. Instead, read about using the if statement. You want to do your program different things, compared on the value of ch[i]. For some cases, just "shift", for others to replace values.
The problem is that the modulo operation can yield negative results.
In Java8 you can use Math.floorMod as an alternative:
class Main{
public static void main(String[] args){
int shift = 1;
String s1 = "abool";
char[] ch=s1.toCharArray();
for(int i=0;i<ch.length;i++){
char c = (char) ((Math.floorMod((ch[i] - 'a' - shift), 26)) + 'a');
System.out.print(c);
}
}
}
An alternative would be to use char c = (char) ( (((ch[i] - 'a' - shift) % 26) + 26) % 26 + 'a');

How do I get the numerical value/position of a character in the alphabet (1-26) in constant time (O(1)) without using any built in method or function?

How do I get the numerical value/position of a character in the alphabet (1-26) in constant time (O(1)) without using any built in method or function and without caring about the case of the character?
If your compiler supports binary literals you can use
int value = 0b00011111 & character;
If it does not, you can use 31 instead of 0b00011111 since they are equivalent.
int value = 31 & character;
or if you want to use hex
int value = 0x1F & character;
or in octal
int value = 037 & character;
You can use any way to represent the value 31.
This works because in ASCII, undercase values are prefixed with 011, and uppercase 010 and then the binary equivalent of 1-26.
By using the bitmask of 00011111 and the AND operand, we covert the 3 most significant bits to zeros. This leaves us with 00001 to 11010, 1 to 26.
Adding to the very good (self) answer of Charles Staal.
Assuming ascii encoding following will work. Updated from the kind comment of Yves Daoust
int Get1BasedIndex(char ch) {
return ( ch | ('a' ^ 'A') ) - 'a' + 1;
}
This will make the character uppercase and change the index.
However a more readable solution (O(1)) is:
int Get1BasedIndex(char ch) {
return ('a' <= ch && ch <= 'z') ? ch - 'a' + 1 : ch - 'A' + 1;
}
One more solution that is constant time but requires some extra memory is:
static int cha[256];
static void init() {
int code = -1;
fill_n (&cha[0], &cha[256], code);
code = 1;
for(char s = 'a', l = 'A'; s <= 'z'; ++s, ++l) {
cha[s] = cha[l] = code++;
}
}
int Get1BasedIndex(char ch) {
return cha[ch];
}
We can get their ASCII values and then subtract from the starting character ASCII(a - 97, A - 65)
char ch = 'a';
if(ch >=65 && ch <= 90)//if capital letter
System.out.println((int)ch - 65);
else if(ch >=97 && ch <= 122)//if small letters
System.out.println((int)ch - 97);
Strictly speaking it is not possible to do it portably in C/C++ because there is no guarantee on the ordering of the characters.
This said, with a contiguous sequence, Char - 'a' and Char - 'A' obviously give you the position of a lowercase or uppercase letter, and you could write
Ord= 'a' <= Char && Char <= 'z' ? Char - 'a' :
('A' <= Char && Char <= 'Z' ? Char - 'A' : -1);
If you want to favor efficiency over safety, exploit the binary representation of ASCII codes and use the branchless
#define ToUpper(Char) (Char | 0x20)
Ord= ToUpper(Char) - 'a';
(the output for non-letter character is considered unspecified).
Contrary to the specs, these snippets return the position in range [0, 25], more natural with zero-based indexing languages.

Character subtraction in String

Here is the code snippet i am trying to figure out whats happening
String line = "Hello";
for (int i = 0; i < line.length(); i++) {
char character = line.charAt(i);
int srcX = 0;
if (character == '.') {
}else{
srcX = (character - '0') * 20;
System.out.println("Character is " + (character - '0') +" " + srcX);
}
}
and executing that code will result to this
Character is 24 480
Character is 53 1060
Character is 60 1200
Character is 60 1200
Character is 63 1260
How a character minus the string which is "0" result in integer?? and where does the system base its answer to have 24,53,60,60,63?
You are allowed to subtract characters because char is an integer type.
The value of a character is the value of its codepoint (more or less, the details are tricky due to Unicode and UTF-16 and all that).
When you subtract the character '0' from another character, you are essentially subtracting 48, the code point of the character DIGIT ZERO.
So, for example, something like '5' - '0' would evaluate to 53 - 48 = 5. You commonly see this pattern when "converting" strings containing digits to numeric values. It is not common to subtract '0' from a character like 'H' (whose codepoint is 72), but it is possible and Java does not care. It simply treats characters like integers.
http://www.ascii.cl/
'0' is 48 in ascii
'H' is 72.
Therefore 72-48 gives you 24

Translating an array of chars into an array of numbers in Java

So, what I need to do is translate an array of chars into an array of numbers.
I know this sounds like an odd request, but here's what I've been trying to do:
Have an array like this:
charArray[0] = e;
charArray[1] = b;
charArray[2] = p;
and have it translatated into:
numArray[0] = 5;
numArray[1] = 2;
numArray[2] = 16;
So it would translate the char into it's position in the alphabet (eg. "a" is the 1st letter, "b" is the 2nd, etc)
What's the best way of doing this? I was going to attempt to do it one by one, but then realized I would have way too many lines of code, it would just be tons of nested if statements, and I figured there's probably some better way to do it.
(My way was going to be if charArray[0] = a then numArray[0] = 1, and go through every single letter like that, until you get to if charArray[0] = z then numArray[0] = 26, but that would require 26 different if statements PER CHAR in the char array, which would be a horrible way of doing it in my opinion, because my char array is extremely long.)
You can use a trick For each index i:
numArray[i] = charArray[i] - 'a' + 1;
A more "by the book" way of doing it is:
final String letters = "abcdefghijklmnopqrstuvwxyz";
. . .
numArray[i] = letters.indexOf(charArray[i]) + 1;
Then any positions i such that charAray[i] is not a lower-case letter will end up as 0 in numArray[i]. With the trick, the value of numArray[i] will be something unpredictable.
You can simply:
numArray[i] = charArray[i] - 'a' + 1;
Explanation:
Looking at the ascci table you'll see the decimal value of each char.
a has the decimal value of 97. So you remove 97 from it and add 1. You get 1.
The same for b...z, removing 97 (a) from 98 (b) will be 1, and you add 1 to get 2.. and so on..
Assume all characters are lowercase, you can write:
numArray[0] = (charArray[0] - 'a' + 1);
If you have lowercase and uppercase, you can use an if statement like:
if (charArray[0] >= 'A' && charArray[0] <= 'Z') {
numArray[0] = (charArray[0] - 'A' + 1);
} else {
numArray[0] = (charArray[0] - 'a' + 1);
}

Categories

Resources