mysql-protocol icon indicating copy to clipboard operation
mysql-protocol copied to clipboard

进制转化的一些疑惑

Open CallMeJiaGu opened this issue 6 years ago • 4 comments

public static final void writeUB3(ByteBuffer buffer, int i) {
		buffer.put((byte) (i & 0xff));
		buffer.put((byte) (i >>> 8));
		buffer.put((byte) (i >>> 16));
	}

不明白,为什么int转为byte类型还需要用 i&0xff呢? 我的理解是因为(byte)的强制转化是针对int类型的低8位的,所以就算i没有进行 &0xff的操作,也是不会影响到该值的吧。 所以高字节的int转低字节的byte是不是可以写成:

public static final void writeUB3(ByteBuffer buffer, int i) {
		buffer.put((byte) (i) );
		buffer.put((byte) (i >> 8));
		buffer.put((byte) (i >> 16));
	}

CallMeJiaGu avatar Oct 31 '18 10:10 CallMeJiaGu

因为存在二进制补码问题

sea-boat avatar Oct 31 '18 14:10 sea-boat

是的,的确存在二进制补码的问题。但是这个问题应该是发生在低位转高位的时候。 下面将byte转为long的时候,考虑到补码的问题,所以需要&0xff。

public long readUB4() {
		final byte[] b = this.data;
		long l = (long) (b[position++] & 0xff);
		l |= (long) (b[position++] & 0xff) << 8;
		l |= (long) (b[position++] & 0xff) << 16;
		l |= (long) (b[position++] & 0xff) << 24;
		return l;
	}

但是像下面这样的高位转低位也存在补码的问题吗?

public static final void writeUB3(ByteBuffer buffer, int i) {
		buffer.put((byte) (i & 0xff));
		buffer.put((byte) (i >>> 8));
		buffer.put((byte) (i >>> 16));
	}

CallMeJiaGu avatar Nov 01 '18 02:11 CallMeJiaGu

你好,你说的是高到低没有问题的,此时写上0xff就是看着明确点

sea-boat avatar Nov 01 '18 07:11 sea-boat

好的,谢谢你的解答

CallMeJiaGu avatar Nov 01 '18 10:11 CallMeJiaGu