Note that there are some explanatory texts on larger screens.

plurals
  1. POUnderstanding Java bytes
    primarykey
    data
    text
    <p>So at work yesterday, I had to write an application to count the pages in an AFP file. So I dusted off my MO:DCA spec PDF and found the structured field <code>BPG (Begin Page)</code> and its 3-byte identifier. The app needs to run on an AIX box, so I decided to write it in Java. </p> <p>For maximum efficiency, I decided that I would read the first 6 bytes of each structured field and then skip the remaining bytes in the field. This would get me:</p> <pre><code>0: Start of field byte 1-2: 2-byte length of field 3-5: 3-byte sequence identifying the type of field </code></pre> <p>So I check the field type and increment a page counter if it's <code>BPG</code>, and I don't if it's not. Then I skip the remaining bytes in the field rather than read through them. And here, in the skipping (and really in the field length) is where I discovered that Java uses signed bytes.</p> <p>I did some googling and found quite a bit of useful information. Most useful, of course, was the instruction to do a bitwise <code>&amp;</code> to <code>0xff</code> to get the unsigned int value. This was necessary for me to get a length that could be used in the calculation for the number of bytes to skip.</p> <p>I now know that at 128, we start counting backwards from -128. What I want to know is how the bitwise operation works here--more specifically, how I arrive at the binary representation for a negative number.</p> <p>If I understand the bitwise <code>&amp;</code> properly, your result is equal to a number where only the common bits of your two numbers are set. So assuming <code>byte b = -128</code>, we would have:</p> <pre><code>b &amp; 0xff // 128 1000 0000-128 1111 1111 255 --------- 1000 0000 128 </code></pre> <p>So how would I arrive at 1000 0000 for -128? How would I get the binary representation of something less obvious like -72 or -64?</p>
    singulars
    1. This table or related slice is empty.
    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