Note that there are some explanatory texts on larger screens.

plurals
  1. POJava int and long : how to change the most significant bit?
    primarykey
    data
    text
    <p>For fun, I've been implementing the DES algorithm in java. (Well, it's not that fun actually). In the algorithm, you handle blocks of 64 bites of data, and I thought : hey, it's perfect, let's use "long" to store my binary data.</p> <p>I then run into a serious trouble that kind of pisses me off : let's say you build a long, like this :</p> <pre><code>long value = 785537; </code></pre> <p>Let's say that you want to set the most significant bit of you value to 1, you would do something like that :</p> <pre><code>value |= 0x8000000000000000l; </code></pre> <p>Pretty straightforward, right ? But it's not working at all. Java has no trouble changing another bit, which means that</p> <pre><code>value |= 0x7000000000000000l; </code></pre> <p>will work. But it won't work if it's the most significant bit.</p> <p>Why ? Is there some way to achieve what I want ?</p> <p>Thanks in advance for your answers.</p> <p>Edit :</p> <p>Here is a sample of a code I wrote, to display a long in a binary form :</p> <pre><code>public static void printBits(long input){ StringBuilder builder = new StringBuilder(); for(int i = 0; i &lt; 64; i++){ if((input &amp; (0x1l &lt;&lt; i)) != 0){ builder.append('1'); } else { builder.append('0'); } } System.out.println(builder); } </code></pre> <p>If I do this :</p> <pre><code>long val = -1; printBits(val); </code></pre> <p>It will print "1111111111111111111111111111111111111111111111111111111111111110" as it's supposed to. If I then type :</p> <pre><code>val |= Long.MIN_VALUE; printBits(val); </code></pre> <p>Or</p> <pre><code>val |= 0x8000000000000000l; printBits(val); </code></pre> <p>It's printing "1111111111111111111111111111111111111111111111111111111111111110" also...</p> <p>If then do the following test :</p> <pre><code>(val &amp; 8000000000000000l) != 0; </code></pre> <p>It's false...</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload