-2

I have one long value and Set Particular bit by converting hexadecimal value.

long l = 4;

long output; //output is 84 if i want set 7th bit (1000 0100) 

same way is long is 7 then output is 87 so how to set particular bit inside long value.

Requirement:

I have to send one byte to server by proper formatting.

Client gives following thing. 1. Whether 7th bit set or not set. 2. One integer value (like 4,5,6,7 etc.) Now I have generate string or decimal (2H) that format as client parameter.

Kamlesh Kanazariya
  • 1,209
  • 2
  • 15
  • 32
  • 1
    Is your question how to set a particular bit, or how to get the value in hexadecimal? You don't have to convert to hexadecimal to set a particular bit. – RealSkeptic May 11 '15 at 08:26
  • I know that how to get hexadecimal from long (Long.toHexString(intValue)) but now I want to set particular bit. – Kamlesh Kanazariya May 11 '15 at 08:28
  • possible duplicate of [How to set/unset a bit at specific position of a long in Java?](http://stackoverflow.com/questions/12015598/how-to-set-unset-a-bit-at-specific-position-of-a-long-in-java) – RealSkeptic May 11 '15 at 08:29

1 Answers1

3

You need to do a bitwise or with the value of the bit.

The value of the bit you can find by shifting 1L the correct number of bits to the left. (Don't forget the L, without that you're shifting the int 1.)

Bitwise or can be done with the | operator in Java.

So the code becomes:

long output = l | (1L << 7);
Hoopje
  • 12,677
  • 8
  • 34
  • 50