在Java中使用char作为无符号16位值? [英] Using char as an unsigned 16 bit value in Java?

查看:361
本文介绍了在Java中使用char作为无符号16位值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要Java中的无符号8位整数,而char似乎是唯一接近它的东西。虽然它的大小是它的两倍,但是它是无符号的,这使得它可以用于我想要的东西(编写一个需要无符号字节的基本仿真器)。问题是我听过其他程序员说不应该以这种方式使用char,而应该只使用int。这是真的,为什么会这样?

I need an unsigned 8 bit integer in Java, and char seems to be the only thing close to that. Although it's double the size, it's unsigned which makes it practical for what I want to use it for (writing a basic emulator which requires unsigned bytes). The problem is that I've heard other programmers say that one shouldn't use char in that manner and should just use int or so. Is this true, and why so?

推荐答案

如果你需要一个无符号的8位整数,那么使用 byte 。在arithemtic操作中(实际上标记的重要性)很容易使其无符号为 byteValue& 0xFF

If you need an unsigned 8 bit integer then use byte. It's easy to make it unsigned in arithemtic operations (where actually sign matters) as byteValue & 0xFF

这篇关于在Java中使用char作为无符号16位值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆