Reputation: 2626
Could anyone please tell me how to convert the unsigned char '0' to a byte in Java ?
Thank you
Upvotes: 1
Views: 201
Reputation: 533790
You can covert it two ways depending on what you are trying to do
char ch = '0';
byte b = (byte) ch; // ASCII value of '0'
or
byte b = (byte) (ch - '0'); // numeric value of 0
or
byte b = (byte) Character.getNumericValue(ch); // numeric value.
The last one is interesting because it gives you the numeric value of all characters, not just '0' .. '9'
for (int ch = Character.MIN_VALUE; ch < Character.MAX_VALUE; ch++) {
int value = Character.getNumericValue(ch);
if (value > 99)
System.out.println("The numeric value for " + (char) ch + " is " + value);
}
prints
The numeric value for ௱ is 100
The numeric value for ௲ is 1000
The numeric value for ፻ is 100
The numeric value for ፼ is 10000
The numeric value for Ⅽ is 100
The numeric value for Ⅾ is 500
The numeric value for Ⅿ is 1000
The numeric value for ⅽ is 100
The numeric value for ⅾ is 500
The numeric value for ⅿ is 1000
The numeric value for ↀ is 1000
The numeric value for ↁ is 5000
The numeric value for ↂ is 10000
Upvotes: 3
Reputation: 2762
You can directly typecast it as follows
byte bValue = (byte)c;
Where c is character you want to convert to byte.
Upvotes: 0
Reputation: 81724
Depends on how we interpret the question, I guess; but simple is often best:
byte b = 0;
This is assuming the quotes around your 0 are for emphasis, not part of the syntax!
Upvotes: 0