How do I shift a byte array n positions to the right? For instance shifting a 16 byte array right 29 positions? I read somewhere it can be done using a long? Would using a long work like this: Long k1 = byte array from 0 to 7 Long k2...

I'm writing code to translate machine code. readFiveBytes is inside of a loop and supposed to take one byte at a time and place each byte into its correct place and return an address in the end. void readFiveBytes(int c) { if (counter != 0) { currentIns = currentIns |...

I am working on bitwise manipulation (in C) and I wanted to know how to check if a bit has toggled between a previous value and the new value. Example : oldValue = 0x0FF //0000 1111 1111 in binary newValue = 0x100 //0001 0000 0000 in binary In this example...

I've been looking at some of these books with fun interview problems. One has a question where one is supposed to write code to flip two bits in a 64-bit integer given the indices of the two bits. After playing around with this for a while I came up with...

I would like to convert (n < 0 ? 1 : 0) into bit twiddling (assuming 2s complement arch). for performance reasons....

I came across this problem wherein all of the program was given barring only a piece of logic. What could be filled in the following problem's missing lines? Problem Statement Jack and Daniel are friends. They want to encrypt their conversation so that they can save themselves from interception by...

Suppose the following: bitstring = numpy.random.random_integers(0,2**32,size=8).astype(numpy.uint32) How can I find out which of the 256 bits are set to 1? I've got this... but this is crazy, isn't it? maximum = (2**32)-1 for checkbit in range (256): yes = bool(numpy.bitwise_and((2**checkbit)%maximum, bitstring[ ( (checkbit // maximum) + checkbit % maximum )...

Good morning, don't know if this question is hitting the right StackExchange network. If not please forgive me. I got an decimal/integer identifier value which i need to split into three separate values. Lets assume we have program ABC. Program ABC is generating the decimal/integer identifier value using this formula:...

I don't know what's going on with this: #define _PACK32(str, x) \ { \ *(x) = ((int) *((str) + 3) ) \ | ((int) *((str) + 2) << 8) \ | ((int) *((str) + 1) << 16) \ | ((int) *((str) + 0) << 24); \ } the str it's...

We are having some small problems when converting data from hex to integer in ruby... We get a hardware signal, which is integer data -> converted to high and low byte, bitwise reversed -> string. Here is a example: Something between 0 and 75 => will be converted to "0x3938"......

Is it possible to shift 0s as you can shift 1s in shifting operation in C? Something like this for (i=0; i<32; i++) { if (data & 0x01) { data |= (1<<i); } else { data &=~ (0<<i); } } I'm checking if some bits are set and depending on...

I've got some code in another language which uses an enum and a list of values from the enum and then uses bitwise to get an integer for the list of values from the enum. HELLO = 1 WORLD = 2 AND = 4 SO = 8 ON = 16...

I have this: int line = 0; line |= (1 << 0); line |= (1 << 1); line |= 0000000000; I was expecting an output of 000000011. But the output is 11. Why is my result truncated? I am using Java. So System.out.print();...

I need to implement as fast as possible left bit shift of a 16-byte array in JavaCard. I tried this code: private static final void rotateLeft(final byte[] output, final byte[] input) { short carry = 0; short i = (short) 16; do { --i; carry = (short)((input[i] << 1) |...

I've been experimenting with changing values for some of the bits for field packing a byte, based on my last question: Field packing to form a single byte However, I'm getting unexpected results based on the values. The top code sample gives me an expected output of 0x91, however if...

The method convertToBinary is used to show the 8bit binary number, public static String convertToBinary(int a){ String binary=""; for(int i=0;i<8;++i){ Integer bit=new Integer(a&1); binary=bit.toString()+binary; a>>=1; } return binary; } public static void main(String[] args) { int a=-9; System.out.println(convertBinary(a)); //11110111 System.out.println(convertBinary(0xaaaa)); //10101010 System.out.println(convertBinary(a&0xaaaa)); //10100010 System.out.println(convertBinary((a&0xaaaa)>>1));//01010001 } The last...

I am learning Bitwise Operators and for that I pulled out an article on tutsplus. Well, it is written quite nicely. I could understand the & and | operator but the ~ is messing things up. For example, as stated there in the article: In fact, just as ! flips...

Can anyone Explain this bitcount method. public static int bitCount(int i) { // Hacker's Delight, Figure 5-2 i -= (i >> 1) & 0x55555555; i = (i & 0x33333333) + ((i >> 2) & 0x33333333); i = ((i >> 4) + i) & 0x0F0F0F0F; i += i >> 8; i...

>>> result = 0 >>> x = -2 >>> >>> for i in range(32): ... c = 1 << i ... if c & x: result |= c ... >>> print(result) 4294967294 As you can see, the expected result should be -2, however the program prints 4294967294, which is the...

I could use this: unsigned long alpha = 140 | 130 << 8 | 255 << 16; to set 140 to the first byte of alpha, 130 to the second and 255 as 3rd. How do I do the opposite (i.e checking a specific byte of alpha) ? alpha &...

My particular case of summing digits deals with colors represented as integer. Java function BufferedImage.getRGB returns image in 0x00RRGGBB format. I'm making a function that gives you grayscale (color independent) sum of colors on the image. Currently, my operation looks very naive: //Just a pseudocode int sum = 0; for(x->width)...

This question already has an answer here: What does the “|” (single pipe) do in JavaScript? 3 answers I've seen a single | being used in code somewhere but I have no idea what it means. I know that || is 'or'. I typed it in the console and...

In some old C/C++ graphics related code, that I have to port to Java and JavaScript I found this: b = (b+1 + (b >> 8)) >> 8; // very fast Where b is short int for blue, and same code is seen for r and b (red & blue)....

Looking at x86 assembly produced by a compiler, I noticed that (unsigned) integer divisions are sometimes implemented as integer multiplications. These optimizations seem to follow the form value / n => (value * ((0xFFFFFFFF / n) + 1)) / 0x100000000 For example, performing a division by 9: 12345678 / 9...

Is this correct way to check if bits are set in some variable and store them in another variable? Just ignore variable names, image[] and mask variables are 1 byte and first_hline_first_row and second_hline_first_row are 2 byte. for(i=0; i<16; i++){ if(image[i] & mask1) first_hline_first_row |= (1<<i); else first_hline_first_row &=~ (0<<i);...

I need to read binary files containing millions of Int16 stored as big endian. My first method was to use BitConverter and Array.Reverse() but that appears too slow for my purpose. Is there a way to do it with bitwise arithmetic instead ?...

I'm looking at the implementation of java.io's DataInputStream.readLong() in SE6: private byte readBuffer[] = new byte[8]; public final long readLong() throws IOException { readFully(readBuffer, 0, 8); return (((long)readBuffer[0] << 56) + ((long)(readBuffer[1] & 255) << 48) + ((long)(readBuffer[2] & 255) << 40) + ((long)(readBuffer[3] & 255) << 32) + ((long)(readBuffer[4]...

This question is similar to this other question; however, I'd like to understand why this is working as it is. The following code: console.log((parseInt('0xdeadbeef', 16) & parseInt('0x000000ff', 16)).toString(16)); console.log((parseInt('0xdeadbeef', 16) & parseInt('0x0000ff00', 16)).toString(16)); console.log((parseInt('0xdeadbeef', 16) & parseInt('0x00ff0000', 16)).toString(16)); console.log((parseInt('0xdeadbeef', 16) & parseInt('0xff000000', 16)).toString(16)); console.log((parseInt('0xdeadbeef', 16) &...

I have created a function which does 64-bit * 64-bit to 128-bit using SIMD. Currently I have implemented it using SSE2 (acutally SSE4.1). This means it does two 64b*64b to 128b products at the same time. The same idea could be extended to AVX2 or AVX512 giving four or eight...

This is an incredibly specific question, as i simply need to know if this pattern has a name and if there is a more effective way of doing it. (disregard the obvious declaration in the for loop) for (int i = 0; i < 8; i++) { int mod =...

This question already has an answer here: What are bitwise shift (bit-shift) operators and how do they work? 5 answers given int a = 1; (00000000000000000000000000000001), what I did is just a=(a<<31)>>31; I assume a should still be 1 after this statement (nothing changed I think). However, it turns...

I'm trying to write hashset in C, and I've found one hash function, that hashes according to bits in data. I have the following structure: struct triple { int a; int b; int c; }; The question is - how to get bit representation from object of type struct triple?...

I have a number of type int. It lies within [0,255]. That is, includes 8 bits. I need to check often say: 2(int) = 00000010(Binary) 1. The bit 6 and bit 7 must be equal to 0 and 1 respectively. And I check it like this: if ((!(informationOctet_ & (1...

As per the C standard the value representation of a integer type is implementation defined. So 5 might not be represented as 00000000000000000000000000000101 or -1 as 11111111111111111111111111111111 as we usually assume in a 32-bit 2's complement. So even though the operators ~, << and >> are well defined, the bit...

I want to create a bitmask and the bitmask offset by offset and length. For example: offset = 8 and length = 4 the bitmask should be: 0xF00 = 3840 in decimal(1111.0000.0000) and the bitoffset should be: 0x100 = 256 in decimal I've tried the following, but that's wrong: ulong...

data |= (1 << 3) sets bit (3) without disrupting other bits. data &= ~(1 << 4) resets bit (4) without disrupting other bits. How can I accomplish both tasks in a single instruction? (As this is really only for readability, I plan on #defineing this in a cute way...

So basically int num = rand(2); //random number from 0-2 int otherNum, otherOtherNum; otherNum = implement this otherOtherNum = implement this For example, if num is 2, otherNum and otherOtherNum must be set to 0 and 1 (or 1 and 0). How would you implement this? Assume you can't use...

I am trying to clearly understand the behaviour of the shift operators (especially for the boundary cases), so I devised a little test written in C++. int a = odd_value; //321 in my case but it should not matter (the last bit to be 1) print(0, a); a = a...

I was looking though some pseudocode for some code and I came across the phrase lowest 32 bits of After a very long time of searching through website I came across the answer: What we want to do is AND operation on 64 bit number and 0xffffffff to get lowest...

I have an array of string bits of variable length and I need to negate them. eg. input array("1", "00101", "101", "0000") output array("0", "11010", "010", "1111") Is there a simple way how to do that?...

There is not my front-end code that is converting X from int to short and save it in a binary stream write(x & 0xFF) write((x & 0xFFFF) >> 8 ) (I am C++ back-end dev and not sure what the language this is.. looks like JS but there is no...

You are given a getTemps() function returns an integer composed of: the daily high temperature in bits 20-29, the daily low temperature in bits 10-19, and the current temperature in bits 0-9, all as 2's complement 10-bit integers. Write a C program which extracts the high, low, and current temperature...

I'm trying to deal with bitboards, which requires me to set a particular bit in a 64-bit unsigned integer. To set bit i, I perform a bitwise OR with the bitboard in question, with a left shifted number. #include <stdint.h> uint64_t kings = 0ULL; // Also tried unsigned long long...

I'm not entirely sure what happens in this process and what the outcome would be. I've never come across using && in a return or especially a single one in the same return statement. bool myfunction(unsigned int x) { return x && !(x & (x - 1)); } I'd love...

Can anyone give a hint how to approach this problem? Given an array A. Is there any subset of array A in which if we do AND of all elements of that subset then output should be in power of two. I've thought of generating a power-set and solving but...

You are given an array A1,A2...AN. You have to tell how many pairs (i, j) exist such that 1 ≤ i < j ≤ N and Ai XOR Aj is odd. Input and Output First line T, the number of testcases. Each testcase: first line N, followed by N...

I am studying the FreeBSH Developers Handbook and there I am seeing this code for Socket programming: struct sockaddr_in sa; sa.sin_addr.s_addr = htonl((((((192 << 8) | 43) << 8) | 244) << 8) | 18); Why is the bitwise shift and or is used here? I know what bitwise shift...

If I have 3 bytes b'\x00\x0c\x00', which can be represented with the bits 00000000 00001100 00000000, how do I then parse the 11th and 12th bit 11 most efficiently? Here positions: ** 00000000 11111110 22222111 tens 87654321 65432109 43210987 ones |||||||| |||||||| |||||||| 00000000 00001100 00000000 ** I have the...

I have an array containing N elements and I need to find the distance between the index of equal elements in a subarray; which we will get in form of query (L R) where L is starting index of subarray and R in ending index. Total No. of array elements...

I'm doing analysis on binary data. Suppose I have two uint8 data values: a = uint8(0xAB); b = uint8(0xCD); I want to take the lower two bits from a, and whole content from b, to make a 10 bit value. In C-style, it should be like: (a[2:1] << 8) |...

The code: echo (5243960811416 & 4040906070209050); Try on http://phptester.net/ and the result (right) will be 20407554584 but on my web hosting it gives -1067281896. There's any workaround to have 20407554584? It's a 32bit limit? Thanks UPDATE /w SOLUTION...

I have small vectors. Each of them is made of 10 integers which are between 0 and 15. This means that every element in a vector can be written using 4 bits. Hence I can concatenate my vector elements and store the whole vector in a single long type (in...

I am trying to figure out how to find all set bits in a hex number and then shift those bits to the left most positions using a 32 bit notation. My program reads in args from the command prompt and then calls the appropriate function and passes either the...

This is from a hacker rank practice problem(not a competition) https://www.hackerrank.com/challenges/flipping-bits. Just doing this for practice. The problem just asks you to take a set number for 32 bit integers and for each one, invert all the bits inside that integer and print out the result Here's my code so...

The question is : x and y are two floating point numbers in 32-bit IEEE floating-point format (8-bit exponent with bias 127) whose binary representation is as follows: x: 1 10000001 00010100000000000000000 y: 0 10000010 00100001000000000000000 Compute their product z = x y and give the result in binary IEEE...

According to w3schools Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc. JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard. So my question comes: if we want to perform a bitwise...

I am writing a function to print bits but i ran into a problem. The two for loops seem identical to me but for some reason the one that is commented out does not print the right bits. int main() { unsigned int bits = 0x570FA1; unsigned int mask =...

what does this piece of code mean ...Can anyone explain how does this work.. sum += (i & (1<<j)) != 0 ? n[j] : 0; full code: int max = (1 << N)-1; //System.err.println(max); String res = "No"; for (int i = 0; i <= max; i++) { long sum...

Here is a C++ class for revering bits from LeetCode discuss. https://leetcode.com/discuss/29324/c-solution-9ms-without-loop-without-calculation For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). Is there anyone can explain it? Thank you so very much!! class Solution { public: uint32_t reverseBits(uint32_t n) { struct bs...

I have an array of ints var ints = [R,B,G,A] and I want to use shifting to get a 32-bit representation var thirtyTwo = AGBR so for example, [255.0, 0.0, 0.0, 255.0] => 0xFF0000FF => 4278190335 I'm attempting to do this with a loop and bitshift: function cArrayToABGR(va) { var...

Excuse me for my english. I have a number of int values stored in it from 0 to 255. To find out what lies in 7 bit number, I translate the numbers into a binary system, then in the line and check the line: if (informationOctet_.substr(6, 1) == "0") {...

Edit: Problem solved, advert your eyes from the below code though, haha, I had some things conceptually wrong from the beginning. I've been trying for longer than I care to admit to count the non-zero bits in a wide variety of 32-bit integers, but always seem a bit off. So...

I'm trying to get an application to XOR two hexadecimal values and output the result as a decimal value. I have searched the Internet for an answer, but every result simply gives a true or false result. The figures I am using as an example are Value 1 = 0F8F...

I am trying to replace the following piece of code // code version 1 unsigned int time_stx = 11; // given range start unsigned int time_enx = 19; // given range end unsigned int time = 0; // desired output while(time_stx < time_enx) time |= (1 << time_stx++); with the...

In IBM OS/390 assembly, I am trying to do the following: I have a set of bits that all end in 2 zeroes: 00xxxxxx 00yyyyyy 00zzzzzz I want to compress them into the following format: xxxxxxyy yyyyzzzz zz... I figure that the order will something like ICM R7,B'1111',FIRSTBUF LOAD 4...

const int BitTable[64] = { 63, 30, 3, 32, 25, 41, 22, 33, 15, 50, 42, 13, 11, 53, 19, 34, 61, 29, 2, 51, 21, 43, 45, 10, 18, 47, 1, 54, 9, 57, 0, 35, 62, 31, 40, 4, 49, 5, 52, 26, 60, 6, 23, 44, 46,...

In ObjC, a bool's bit pattern could be retrieved by casting it to a UInt8. e.g. true => 0x01 false => 0x00 This bit pattern could then be used in further bit manipulation operations. Now I want to do the same in Swift. What I got working so far is...

Given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e g , M becomes a substring of N located at i and starting at j) Example Given N=(10000000000)2, M=(10101)2,...

I am trying to come up with a function int rotateRight(int x, int n) that Rotate x to the right by n. For example,rotateRight(0x87654321,4) = 0x76543218. This is what I have so far int rotateRight(int x, int n) { int mask = (((1 << n)-1)<<(32-n)); int reserve = (int)((unsigned) (x&mask)...

I wanted to try to get only the four bits from the right in a byte by using only bit shift operations but it sometimes worked and sometimes not, but I don't understand why. Here's an example: unsigned char b = foo; //say foo is 1000 1010 unsigned char temp=0u;...

I am trying to flip the bits of an unsigned 32-bit integer and output the resultant integer. The following is my code. int numberOfTries = Convert.ToInt32(Console.ReadLine()); for (int i = 0; i < numberOfTries; i++) { uint input = Convert.ToUInt32(Console.ReadLine()); byte[] bInput = BitConverter.GetBytes(input); if (BitConverter.IsLittleEndian) Array.Reverse(bInput); byte[] result =...

In just intonation theory, a type of music theory, intervals between notes are expressed with rational numbers. Doubling a frequency with a 2:1 ratio brings it up an octave and a 1:1 ratio is no change; a unison. So if I have an interval n that is larger than an...

I'm trying to create a double by appending the binary representations of two ints. This is what I have now: int i = arc4random(); *(&i+1) = arc4random(); double d = *(double*)&i; I hoped the double pointer would also use the value in the &i+1 address, and this is indeed the...

I've been following this tutorial, it's quite helpful and most things are making sense. If you look on page 34 you'll see this snippet of code: } else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) { // Read the data SocketChannel sc = (SocketChannel)key.channel(); // ... } What exactly is going...

Using bitwise operator how can I test if the n least significant bits of an integer are either all sets or all not sets. For example if n = 3 I only care about the 3 least significant bits the test should return true for 0 and 7 and false...

I'm working on a function that returns 1 when x can be represented as an n-bit, 2’s complement number and 0 if it can't. Right now my code works for some examples like (5,3),(-4,3). But I cant get it to work for instances where n is bigger than x like...

Given a 64 bit number, I need to extract every other bit from it, and convert it into a number: decimal: 357 binary: 0000 0001 0110 0101 odd bits: 0 0 0 1 1 0 1 1 decimal: 27 Any idea of a good algorithmic way to do it? And...

I have the following code int n = 50; while(n) { //1 if(n & 1) cout << "1" << endl; //2 //right shift the number so n will become 0 eventually and the loop will terminate n >>= 1; //3 } When we use bitwise and 1 (& 1) with...

I have an int, and I would like to get the 19 most significant bits in java. I tried all sorts of methods, none of them work. Can someone please help me?

The Problem Hi there, i recently moved to using a binary representation for a domain in my program, this enhanced the speed of calculations with that domain, but i now need a method of generating ints based on an input number of bits needed. My application is in Java so...

I was trying to solve an old question: Write a function that add two [integer] numbers A and B. You should not use + or any arithmetic operators. The best solution is like this, quote from here: For a + b in any base, we can treat the plus as...

given a number (int a = 0XABCDE98) i am trying to set the D bit to 6. ie after the Bit manipulation the number should be (0XABC6E98). I have written the small C program to do the bit manipulation, but somehow i am not able to see the correct bit...

I have the following problem I am unable to solve gracefully. I have a data type that can take 3 possible values (0,1,2). I have an array of 20 element of this data type. As I want to encode the information on the least amount of memory, I did the...

Using redis#Setbit to set bit in a key like: redis.Do("SETBIT", "mykey", 1, 1). When I read it using redis#Get like redis.Do("GET", "mykey"), I get a bit string. How do I unpack the string so I can get a slice of bools in Go? In Ruby, you use String#unpack like "@".unpack...

I'm working on a Python Application that reads from a binary file, pulls a byte that then references a list. This is essentially what I'm doing. list = [x for x in range(0, 340)] index = struct.unpack('<b', file.read(1)) print(list[index]) The problem is that the file I'm reading from, the 8th...

strcat(b, ((x & z) == z) ? "1" : "0"); I understand strcat() function and the conditional (ternary) operator. But I don't know what (x & z) == z means....

Most are probably familiar with this problem but for those who are not: Given 32-bit unsigned integers flip their bits and print the resulting integers. I was hoping that someone can give me clueson how to solve this in Java. Now I would normally provide some code i have tried...

I am trying to perform a bitwise or on a byte value I have in Java. For example, I am running: byte b = (byte)0b11111111; int result = 0 | b; My expected result for this would be 0b00000000 00000000 00000000 11111111, or 255. However, I am receiving -1, or...

Consider the following enumeration: [Flags] public enum EnumWithUniqueBitFlags { None = 0, One = 1, Two = 2, Four = 4, Eight = 8, } [Flags] public enum EnumWithoutUniqueFlags { None = 0, One = 1, Two = 2, Four = 4, Five = 5, } The first one has...

This question already has an answer here: C#. Logical riddle with bit operations. Only one bit is set? 3 answers I'm receiving a 3-byte message back from a serial device when I send it a query in my C# application. The entire message should have at most one bit...

I have the struct below typedef struct fpButtons { /** BYTE 0 **/ uint8_t button_1:1; uint8_t button_2:1; uint8_t button_3:1; uint8_t button_4:1; uint8_t button_5:1; uint8_t button_6:1; uint8_t button_7:1; uint8_t button_8:1; /** And BYTE 2 which I didn't paste to save SO's space lol **/ // button_9:1 to button_16:1 } FP_BUTTONS; And...

I have the following question: What will the output be when the following program runs: using System; class Example{ public static void Main(){ int t; byte val; val=123; for(t=128;t>0;t=t/2){ if((val &t)!=0) console.Write("1 "); if((val &t)==0) console.Write("0 "); } } } A.0 0 1 1 1 0 1 1 B.1 1...

I've come across some code which has the bit masks 0xff and 0xff00 or in 16 bit binary form 00000000 11111111 and 11111111 00000000. /** * Function to check if the given string is in GZIP Format. * * @param inString String to check. * @return True if GZIP Compressed...

Is there any way of finding efficiently (bitwise operations) the distance (not Hamming Distance!) of two 8-bit binary strings? Each byte is guaranteed to have only one bit set. Like: a=0 0 0 0 0 0 0 1 b=0 0 0 1 0 0 0 0 0 0 0 1...

I have a char (input) array with size 60. I want to write a function that returns certain bits of the input array. char input_ar[60]; char output_ar[60]; void func(int bits_starting_number, int total_number_bits){ } int main() { input_ar[0]=0b11110001; input_ar[1]=0b00110011; func(3,11); //want output_ar[0]=0b11000100; //least significant 6 bits of input_ar[0] and most significant...

How can I count the number of leading zeros in a 128-bit integer (uint128_t) efficiently? I know GCC's built-in functions: __builtin_clz, __builtin_clzl, __builtin_clzll __builtin_ffs, __builtin_ffsl, __builtin_ffsll However, these functions only work with 32- and 64-bit integers. I also found some SSE instructions: __lzcnt16, __lzcnt, __lzcnt64 As you may guess, these...

As part of my CS classes I've recently completed the pretty popular "Data Lab" assignments. In these assignments you are supposed to implement simple binary operations in C with as few operations as possible. For those who are not familiar with the "Data Lab" a quick overview about the rules:...

Following are results of running the bin builtin function on the Python 2.7.2 interpreter: bin(5) => '0b101' bin(-5) => '-0b101' bin(5&-5) => '0b1' With infinite bits and 2's complement: +5 = 0000...0101 -5 = 1111...1101 Then why is 5&-5 = 0000...1? Shouldn't it be 0000...101? What's the explanation for this?...

I am getting mad, i need to create a token using this operator PHP a = "hello"; b = "world"; token = a | b; well i need create the same in java [android] but i ever get error. I alredy try to: - cast the 2 strings to long...

Here is the code: int i = 200; byte b = (byte) 200; System.out.println(b); System.out.println((short) (b)); System.out.println((b & 0xff)); System.out.println((short) (b & 0xff)); Here is the output: -56 -56 200 200 Bitwise AND with 0xff shouldn't have changed anything in b, but apparently it does have an effect, why?...