考虑数字 123 = 01111011 和 128 = 10000000 .当我们将它们与在一起时,我们得到 0 或非零数字,这取决于 128 中的 1 是否与 1 或 0 . 10000000&01111011----------00000000 在这种情况下,答案是 0 ,我们的第一位为0.往前看,我们将 64 = 01000000 ,然后与 123 进行相加.注意 1 向右移动. 01000000&01111011----------01000000 这次与123进行与运算将产生一个非零数字,第二位为1.重复此过程. 第一段代码(大写): 此处65503是否定值,. 32 = 0000 0000 0010 0000〜32 = 1111 1111 1101 1111 从本质上讲,我们通过对32取反,然后通过与运算从小写字母中减去32.众所周知,从小写ASCII值字符中减去32会将其转换为大写.// following code prints out Letters aA bB cC dD eE ....class UpCase {public static void main(String args[]) { char ch; for(int i = 0; i < 10; i++) { ch = (char)('a' + i); System.out.print(ch); ch = (char)((int) ch & 66503); System.out.print(ch + " ") } }}Still learning Java but struggling to understand bitwise operations. Both codes work but I don't understand the binary reasons behind these codes. Why is (int) casted back to ch and what is 66503 used for that enables it to print out different letter casings.//following code displays bits within a byteclass Showbits { public static void main(String args[]) { int t; byte val; val = 123; for(t = 128; t > 0; t = t/2) { if((val & t) != 0) System.out.print("1 "); else System.out.print("0 "); } } } //output is 0 1 1 1 1 0 1 1For this code's output what's the step breakdown to achieve it ? If 123 is 01111011 and 128 as well as 64 and 32 is 10000000 shouldnt the output be 00000000 ? As & turns anything with 0 into a 0 ? Really confused. 解决方案 Second piece of code(Showbits):The code is actually converting decimal to binary. The algorithm uses some bit magic, mainly the AND(&) operator.Consider the number 123 = 01111011 and 128 = 10000000. When we AND them together, we get 0 or a non-zero number depending whether the 1 in 128 is AND-ed with a 1 or a 0. 10000000& 01111011---------- 00000000In this case, the answer is a 0 and we have the first bit as 0.Moving forward, we take 64 = 01000000 and, AND it with 123. Notice the shift of the 1 rightwards. 01000000& 01111011---------- 01000000AND-ing with 123 produces a non-zero number this time, and the second bit is 1. This procedure is repeated.First piece of code(UpCase):Here 65503 is the negation of 32. 32 = 0000 0000 0010 0000~32 = 1111 1111 1101 1111Essentially, we subtract a value of 32 from the lowercase letter by AND-ing with the negation of 32. As we know, subtracting 32 from a lowercase ASCII value character converts it to uppercase. 这篇关于JAVA逐位代码用途的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!