• Post Reply Bookmark Topic Watch Topic
  • New Topic

string + int preceded by zeros  RSS feed

 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


the above code outputs : 
hello8


how is 8 calculated ?

if my w value is 0011 its 9. How is this ??
 
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Numbers literals, that start with zero, are considered Octal numbers. Hence, 0011 is a base 8 number, that is, of course, equals 9 when converted to decimal (base 10).

Henry
 
shambhavi sivan
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oh yeah right !!!

ok fine , so then , if i want to append  a binary value 0010 to  a String , how do i do it ?

if i try the following :

int w=0b0010;
   String s="message";
   s=s+w;
        System.out.println(s);


again it takes the decimal value and prints message2
 
Sheriff
Posts: 4294
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wouldn't take and decimal to binary (I don't think it's possible), but Integer to binary will work.
 
shambhavi sivan
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

   int w=0b0010;
   String s="message";
   s=s+w;
        System.out.println(s);

the above outputs message2

any way to get output as message0010 ?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
shambhavi sivan wrote:
any way to get output as message0010 ?


What's wrong with using the toBinaryString() method that Knute mentioned?


Also, pointing out something that you probably already figured out, an int variable holds an integer. Period. It is a number only. It doesn't have a concept of the base, of number of digits, of formatting of any kind. The fact that it is binary, due to "0b", and 4 digits in length, is simply the compiler processing the literal. That information is *not* available to the program.... So, you are responsible for formatting the number to a string (as binary and as four digits). There is no way that it can be done automagically.

Henry
 
shambhavi sivan
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
okay thanks everybody for the replies !
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!