简体   繁体   English

如何将char转换为byte?

[英]How to convert char to byte?

I was studying an open source code where I came across the following line 我正在研究一个开源代码,我遇到了以下几行

stringBytes[i] = (byte) (stringChars[i] & 0x00FF);

Can someone explain what is actually happening in this line ??? 谁能解释一下这行中究竟发生了什么?

Char consists of 2 bytes in Java and of course byte is single byte. Char由Java中的2个字节组成,当然字节是单字节。

So in this operation: 所以在这个操作中:

stringBytes[i] = (byte) stringChars[i] & 0x00FF

A char value (16 bits) is being binary ANDED with number 0x00FF (binary: 0000 0000 1111 1111) to make it one byte. char值(16位)是二进制ANDED ,其编号为0x00FF(二进制:0000 0011 1111 1111),使其为一个字节。

By binary ANDING with 8 0s and 8 1s you're basically masking off 8 left most OR most significant bits (MSB) of the char value thus leaving only 8 right most or least significant bits (LSB) intact. 通过使用8 0s and 8 1s二进制ANDING,您基本上屏蔽了char值的8个最左或最高有效位(MSB),因此仅保留8个最右或最低有效位(LSB)。 Then code is assigning resulting values to a byte by using cast (byte) , which is otherwise an int value. 然后代码通过使用cast (byte)将结果值分配给一个字节,否则为int值。

ANDing with 0x00FF retains only the last 8 significant bit and zeros others bits. 与0x00FF进行AND运算仅保留最后8位有效位,并将其他位置零。

E.g.:
0xD2A5 & 0x00FF = 1101001010100101 & 0000000011111111 = 0000000010100101 = A5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM