-2

I have a String which contains a binary value ( 101101 ). now I want to check if the last letter is 1 and if so change it to 0 . how can I do that ?

Aida E
  • 1,108
  • 2
  • 22
  • 40
  • 1
    What have you already tried, and in what way is this "changing the order" as per your title? – Jon Skeet Aug 15 '12 at 12:16
  • 1
    From what you describe, how is this any different from [this question](http://stackoverflow.com/questions/1660034/replace-last-part-of-string)? – thegrinner Aug 15 '12 at 12:18

5 Answers5

6
String result = "101101".substring(0,5) + "0";

why checking? The last character will always be 0, regardless if it was 1 or 0 before...

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
3

You can write

int i = 0b101101;
if (i & 1 != 0)
   i = i & ~1;

or much simpler

i &= ~1; // sets lowest bit to 0.
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
3

Simple version;

String binary = "101101";

binary = binary.substring(0, binary.length() - 1) + "0";

Example here.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
1

One possible solution:

    String k = "101101";

    System.out.println(k);

    int len = k.length();
    char[] charr = k.toCharArray();
    if(charr[len - 1] == '1') {
        charr[len - 1] = '0';
    }
    k = new String(charr);

    System.out.println(k);
Less
  • 3,047
  • 3
  • 35
  • 46
  • 2
    You can remove the if statement. The last digit will always be `0`. – Zéychin Aug 15 '12 at 12:38
  • If you keep removing bits you have Andreas_D's solution. ;) – Peter Lawrey Aug 15 '12 at 12:40
  • 2
    yeah, I also forgot to mention - beside being one possible, this is probably the worst solution to this problem... ever :) – Less Aug 15 '12 at 12:43
  • that was the first post that I saw , now how can I remove the last character ? – Aida E Aug 15 '12 at 12:56
  • @matarsak Why do you want to remove the last character? Everyone has answered your initial question. Are you suggesting that you want something else now? – maba Aug 15 '12 at 13:10
1
int binary = 0b101101;

if ( binary % 2 != 0 )
{
    binary = binary ^ 1b;
}
DavidS
  • 1,660
  • 1
  • 12
  • 26