• Post Reply Bookmark Topic Watch Topic
  • New Topic

counting number of bits for char representation  RSS feed

 
Abigail Decan
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i need to show that there are 16 bits for a char variable.

i tried converting it to an int and then apply the bitCount method but that gave an output of 3.
what method should i use?
 
Paweł Baczyński
Bartender
Posts: 2077
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What char do you try to convert to int? It can't be just any char. It should be Character.MAX_VALUE (because chars are unsigned -- it would be -1 if they were signed).
 
Abigail Decan
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i was trying to print 'a'.
thanks, this worked.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, do you understand why the answer was 3 when you tried with the character 'a'?

The character code for 'a' is 97, or in hexadecimal: 0x0061, or in binary: 0b0000000001100001

The method Integer.bitCount() counts how many bits of the number you pass are set to 1. As you can see, in the character code for 'a', three bits are set to 1.
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yup, reading the javadocs of a method one intends to use definitely helps
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!