• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 421
  • Last Modified:

Lower 8-bits of integer

Given an integer of max length 16-bits how does one read the lower 8-bits, or is this not really a question.

I read that a java method converts the lower 8-bits of its integer param and converts it to the ASCII equiv.

Cheers/
0
robert_83
Asked:
robert_83
  • 7
  • 2
1 Solution
 
TimYatesCommented:
int lower = full & 0xFF ;
0
 
TimYatesCommented:
char ch = (char)( theInt & 0xFF ) ;
0
 
TimYatesCommented:
To get the 8 bits above that, you'd do:

char ch = (char)( ( theInt >> 8 ) & 0xFF ) ;
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

 
TimYatesCommented:
these examples assume that "full" or "theInt" is you int variable :-)
0
 
robert_83Author Commented:
Could you briefly explain the theory of suppose i supply 8000, how to get the lower 8-bits.

This question originated from using DataInputStream readChar, then output the char. No matter what character it read from the text file it always outputted '?'

0
 
TimYatesCommented:
"&" does a bitwise AND on the integer value...

0xFF is 11111111 in binary, so say you have the number 345, in binary, that is:

101011001

so, if we AND it wil 0xFF:

101011001 (345) AND
011111111 (255 -- padded on the left with a zero)
-------------
001011001 (89)

Hope this explains it?

Let me know if you need more of an explanation...

Tim
0
 
TimYatesCommented:
Ahhh...using your example:

1111101000000 (8000) AND
0000011111111 (255 -- 0xFF)
------------------
0000001000000 (64)
0
 
robert_83Author Commented:
thanks for the reply, clear and concise.

I have a text file containing "r".

dis = DataInputStream(new FileInputStream(file));
char c = dis.readChar()
System.out.println(c);
output = ?

Why does it output ?.

Cheers/
0
 
TimYatesCommented:
If it's a text file, use a Reader:

BufferedReader br = new BufferedReader( new FileReader( file ) ) ;
char c = (char)br.read() ;
System.out.println( c ) ;

should work...

if not, it is probably an encoding problem...
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

  • 7
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now