so I'm starting to learn java and I was wondering if I could use the "%n" parameter (from C printf()), which should write the number of bytes written up to the "%n" parameter:
this is it's use in C:
#include <stdio.h>
int main()
{
int val;
printf("ciao %n ciao\n", &val);
printf("val = %d\n", val);
return 0;
}
prints:
ciao ciao
val = 5
But when I try to use it in java:
public class CharTest
{
public static void main(String[] argv)
{
int value;
System.out.printf("\nNumber of bytes written up to now: %n\n", &value);
System.out.println(value);
}
}
The java compiler gives me this message:
CharTest.java:20: error: illegal start of expression
System.out.printf("\nNumber of bytes written up to now: %n\n", &value);
^
1 error
How do I solve this?
In C you can pass parameters by reference or change the value of variables passed to functions by passing a pointer to them, the %n specifier stores the number of characters written so far in value and in order to do that you had to pass the pointer to value with &value.
In Java it's not possible to pass parameters by reference or to pass pointers of variables and the same syntax is not possible, & operator is bitwise and. The printf %n specifier in Java prints a platform specific line separator.
You can't do it in Java at all. There is no conversion that would correspond to %n of the printf C. Instead, you can use the String.format to format the string
String s = String.format("\nNumber of *%s* written up to now: ", "characters");
then check the number of characters in s, and format that separately:
int len = s.length()
String result = String.format("%s%d\n", s, len);
Lastly, do note that unlike in C where char is exact synonym of byte, in Java the strings do not even consist of bytes, but Unicode/UTF-16 codepoints. Asking how many bytes are written by a string formatting operation is meaningless.
Related
I'm trying to find a way to convert a char (Precondition is the char can only be '0' or '1') into an actual bit in Java. I'm not sure if Java has some built-in functionality for this, or if there is an algorithm that can be implemented to do so.
I need to implement the following class:
public void writeBit(char bit) {
//PRE:bit == '0' || bit == '1'
try {
} catch (IOException e) {
System.out.println(e);
}
}
I cannot change the method structure in any way. I am implementing Huffman Encoding and have an array of Strings that represent the encodings for every character within an input file. For example, 'A' or array[65] contains the String: "01011". So if I see the letter A in my file, I need to use writeBit to write out A's respective String to a binary file. Every time I reach 8 bits (one byte) I will call writeByte to send those 8 bits to the binary file, then reset some sort of counter variable to 0 and continue.
What I'm stuck on is how I am supposed to convert the char bit into an actual bit, so that it can be properly written out to a binary file.
Java does not have a primitive data type representing a single bit. On many hardware architectures, it is not even possible to access memory with that granularity.
When you say "an actual bit", then, I can only assume that you mean an integer value that is either 0 or 1, as opposed to char values '0' and '1'. There are numerous ways to perform such a conversion, among them:
byte the_bit = bit - '0';. This takes advantage of the fact that char is an integer type, and that the decimal digits zero and one are encoded in Java with consecutive character codes.
byte the_bit = (bit == '0') ? 0 : 1;. This just explicitly tests whether bit contains the value '0', evaluating to 0 if so or 1 if not.
It gets more complicated from there, for example:
byte the_bit = Byte.parseByte(String.valueOf(bit));. This converts the char to a string containing (only) that char, and then parses it as the string representation of a byte.
All of the above rely to one degree or another on the precondition given: that bit does not have any value other than '0' or '1'.
With that said, I think anything like this is probably the wrong approach for implementing a Huffman encoding, because Java Strings are an unlikely, very heavyweight, representation for the bit strings involved.
You can use Integer.parseInt(String s, int radix) or Integer.parseUnsignedInt(String s, int radix) with radix 2, to convert from a "binary digits string" to internal int java integer form.
public static void main(String[] args) {
int num = Integer.parseInt("101010", 2);
// print 42
System.out.println(num);
}
And reversely with method Integer.toBinaryString(int i) you can generate the binary string representation:
// print 101010
System.out.println(Integer.toBinaryString(42));
Similarly you can use Byte.parseByte(String s, int radix) to parse a byte:
public static void main(String[] args) {
byte num = Byte.parseByte("101010", 2);
// print 42
System.out.println(num);
}
This question already has answers here:
Char - Java not working as intended / my code
(4 answers)
Closed 3 years ago.
I am seeing a tutorial on udemy and there the instructor says that we can store the integer variable in the char data type. But when I try to print the value ... nothing shows up
I tried assigning the "char one" value to integer variable and then get the output from int variable,It works but why can not I use the char to output the value
public static void main(String[] args) {
char one = 10;
System.out.println(one);
}
If you look at the ASCII table you would see that the character 10 represents the newline character.
This can be proved by the code below:
public static void main(String[] args) {
char one = 10;
//no newline added by print, but println adds a newline implicitly
System.out.print("Test");
System.out.print(one);
System.out.print("Test");
}
The output is:
Test
Test
Although I used System.out.print a newline was still added in the output after the first Test. So you see something was actually printed.
Furthermore, when you pass a char to the System.out.println() the char is converted to its String representation as per the ASCII table by invoking the String.valueOf(char) as char is a primitive.
For Objects when you pass a reference in the System.out.println() the toString() method of the object would be called to get its String representation.
If you change the value to char one = 65 you would see the letter A printed.
In Java char type is an int, therefore they can be converted char <-> int.
When you print an int - you get an integer number. When you print char - you get an ASCII character. char ch = 10 - is not printable character.
char ch = 'A';
System.out.println(ch); // print 'A'
int code = ch;
System.out.println(code); // print 65 - ASCII code of 'A'
Adding to the above answers, if you want to output the int value from the variable "one", a cast would work:
char one = 10;
System.out.println((int) one);
If you take a look at the ASCII Table, you can see the value of 10 is LF which is a new line. If you print this alone, it will appear to be doing nothing because it is just a new line.
However if you modify the code a bit to print some actual characters on both side of the LF char:
char c1 = 70;
System.out.print(c1);
char one = 10;
System.out.print(one);
char c2 = 71;
System.out.print(c2);
This will output:
F
G
On separate lines due to the newline in between, without it they would have printed on the same line.
Additionally you can see on that table 70 corresponds with F, and 71 with G.
Note: Java does not technically use ASCII, but rather a different encoding depending on your environment(commonly UTF-16 or ISO-8859-1), however, the characters are usually equivalent to ASCII for the amount of values the ASCII table contains (a superset). For example char c1 = 202 will print Ê for me, which is not an ASCII value.
You are misinterpreting your output and drawing the wrong conclusion.
A char is a UTF-16 code unit. UTF-16 is a character encoding for the Unicode character set. UTF-16 encodes a Unicode codepoint with one or two UTF-16 code units. Typically, if it might be two code units, you'd use String or char[] instead of char. But if your codepoint is known to take only one UTF-16 code unit, you could use char.
The codepoint you are using is U+000A 'LINE FEED (LF)'. It does take one UTF-16 code unit \u000a, which is convertible from the integer value 0xa or 10. If you inspect your output carefully, you'll "see". Perhaps adding output before and after would help.
import java.util.*;
public class test
{
public static void main(String[] args)
{
int i = 123;
String s = Integer.toString(i);
int Test = Integer.parseInt(s, s.charAt(0)); // ERROR!
}
}
I want to parse the input string based on char position to get the positional integer.
Error message:
Exception in thread "main" java.lang.NumberFormatException: radix 49 greater than Character.MAX_RADIX
at java.lang.Integer.parseInt(Unknown Source)
at test.main(test.java:11)
That method you are calling parseInt(String, int) expects a radix; something that denotes the "number system" you want to work in, like
parseInt("10", 10)
(10 for decimal)! Instead, use
Integer.parseInt(i)
or
Integer.parseInt(i, 10)
assuming you want to work in the decimal system. And to explain your error message - lets have a look at what your code is actually doing. In essence, it calls:
Integer.parseInt("123", '1')
and that boils down to a call
Integer.parseInt("123", 49) // '1' --> int --> 49!
And there we go - as it nicely lines up with your error message; as 49 isn't a valid radix for parsing numbers.
But the real answer here: don't just blindly use some library method. Study its documentation, so you understand what it is doing; and what the parameters you are passing to it actually mean.
Thus, turn here and read what parseInt(String, int) is about!
Integer.parseInt(parameter) expects the parameter to be a String.
You could try Integer.parseInt(s.charAt(0) + ""). The +"" is to append the character to an empty String thereby casting the char to String and this is exactly what the method expects.
Another method to parse Characters to Integers (and in my opinion much better!) is to use Character.getNumericValue(s.charAt(0));
Check this post for further details on converting char to int
Need to convert String.valueOf(s.charAt(0)) to String.valueOf(s.charAt(0)) i.e. Char to String.
import java.util.*;
public class test
{
public static void main(String[] args)
{
int i = 123;
String s = Integer.toString(i);
int Test = Integer.parseInt(String.valueOf(s.charAt(0)));
}
}
Let use what we have here.
To parse one digit from a String into an integer. Use getNumericValue(char)
In your case, to get the first character into a number :
int n = Character.getNumericValue(s.charAt(0));
Be aware that you should take the absolute value if you integer can be negative.
String b = "5A";
int bConv = Integer.parseInt(b, 16);
char $2 = bConv;
When I try this I get a possible loss of precision error warning.
That's because an int by default takes 4 bytes, a char takes 2 bytes. So by casting you might lose data.
An explicit cast will remove the warning:
String b = "5A";
int bConv = Integer.parseInt(b, 16);
char $2 =(char)bConv;
Side note: In my opinion $2 is a bad name for a variable.
UPDATE
Is there a better way to represent characters using hexadecimal values?
Don't know if it can be considered better, but you can assign the hex value directly to the character:
char myHexChar = 0x5A; //0x tells the compiler that the value is in hex format
If you print that variable, you'll get Z
In file data.hex, the data is given in hexadecimal form where the first digit of hexadecimal number is always less than 8. Eg.
01FC 04BF 04C0 04C1 04C2 24C3 04C4 34C5 ...
To parse this file and store the values in shrt[] array i have written this code
void read_hex_short(String filename, short[] shrt, int x, int y) throws Exception
{
String str;
Scanner s=new Scanner(new BufferedReader(new FileReader(filename)));
for(int i=0;i<height*width;i++)
{
str= s.next(); // i have tried str="0x"+s.next() but it didn't work
image[i]=(short)Integer.parseInt(str);
}
s.close();
}
But i am getting NumberFormatException which arises while passing the first string i.e. 01FC only.
How can i parse these hexadecimal values and store them in the shrt[] array?
You should be using Integer.parseInt(str, 16) to tell it to use hex.
You should also be aware that any values greater than 0x7FFF will end up being negative in your array: Java doesn't have any unsigned numeric types (unless you count char).
You can use Short.parseShort(str, 16) to parse HEX. This will avoid the need to cast it to short from an int.
Give parseInt method a radix parameter. Like this:
Integer.parseInt(str, 16)