Home > Mobile >  how to inteprete a char, when I want to convert a char to a hexadecimal, as a integer with 32 bits (
how to inteprete a char, when I want to convert a char to a hexadecimal, as a integer with 32 bits (

Time:12-17

I have a quick question about the Char data type. It's about an exercise from university, I'm not allowed to use any prefabricated Java methods, such as parse int or something.

In the exercise, you have a char array that represents hexadecimal numbers and has this content, for example:

char[] test={'0','x','F','F'); or char[] test={'F','F',); 

and now I should convert this char to a long. But before that, I should check if my hexadecimal number, is convertible to a long. So simplified the task says I should check if my hexadecimal number, which I am given as a char, can be converted into a long.

AND now we come to my problem.

If I want to convert this char into a long, I first check whether this is allowed. A char has 16 bits and a long 64 bits. That means I can only convert 4 chars to a long or (64/16=4)? Is that what they mean by check if you can convert the char into a long value?

If so, so if I am to check the bits is it correct that I do this with 16 bits? Because later when I convert my array of chars to a long, I do it with the integer or not? e.g. F is 70 when I look to my char, and 70 is represent as an integer.

Because when I make my char a long value, I do that via the integer representation of the char, right? And then I don't actually have a char any more, but an integer with 32 bits.

And an integer has 32 bits, does that mean I can only convert 2 char values to a long?

CodePudding user response:

Look at

char[] test={'0','x','F','F');
char[] test={'F','F',); 

Evidenty they want

long n = 0xFFL = 255L;

in both cases "0x" being optional.

So a character array containing a text representation of a hexadecimal number, converted to long.

That is a totally different

CodePudding user response:

Since each hexadecimal digit corresponds to exactly 4 bits of the the resulting integer respectively long value, all you have to do is check the number of digits. For a 16-bit integer, you can have at most 4 hexadecimal digits. For 32-bit integer, 8 hexadecimal digits are allowed; and for 64-bit integer (aka long), 16 hexadecimal digits are the limit.

Since Java does not support unsigned types, the most significant digit must be '7' or lower if your number uses the maxium allowed number of digits.

Please keep in mind that the prefix {'0','x' does not count towards the allowed number of digits.

  • Related