Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

进制转化的一些疑惑 #6

Open
CallMeJiaGu opened this issue Oct 31, 2018 · 4 comments
Open

进制转化的一些疑惑 #6

CallMeJiaGu opened this issue Oct 31, 2018 · 4 comments

Comments

@CallMeJiaGu
Copy link

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));
	}
@sea-boat
Copy link
Owner

因为存在二进制补码问题

@CallMeJiaGu
Copy link
Author

是的,的确存在二进制补码的问题。但是这个问题应该是发生在低位转高位的时候。
下面将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));
	}

@sea-boat
Copy link
Owner

sea-boat commented Nov 1, 2018

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

@CallMeJiaGu
Copy link
Author

好的,谢谢你的解答

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants