在Java中从short转换为byte,反之亦然 [英] convert from short to byte and viceversa in Java

查看:144
本文介绍了在Java中从short转换为byte,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将short转换为2个字节...然后从这2个字节尝试获得相同的short值。为此,我写了这段代码:

I'm trying to convert a short into 2 bytes...and then from those 2 bytes try to get the same short value. For that, I've written this code:


        short oldshort = 700;

        byte 333= (byte) (oldshort);
        byte byte2= (byte) ((oldshort >> 8) & 0xff);

        short newshort = (short) ((byte2 << 8) + byte1);

            System.out.println(oldshort);
        System.out.println(newshort);

对于700(oldshort)的值,newhosrt是444.经过一些测试,它看起来像是\\ t此代码仅适用于某些值。就像...如果oldshort = 50,那么它将正常工作..但如果它是-200,或更大的值超过127(我认为)它不起作用。我想有签名的字节,二的补码值等问题......但我无法弄清楚如何解决它。

For the value of 700 (oldshort), newhosrt is 444. After some testing, it looksl ike \tThis code only works for some values. Like...if oldshort=50, then it will work fine..but if it is -200, or bigger values than 127 (i think) it doesn't work. I guess that there is a problem with the signed bytes, two's complement value, etc...but I can't figure out how to solve it.

有什么想法吗? ?在java中以任何本地方式执行此操作?在此先感谢!

Any idea?? Any native way to do this in java?? Thanks in advance!

推荐答案

重新组合时,需要屏蔽byte1以阻止它进行符号扩展。

When recombining, you need to mask the byte1 to stop it being sign extended.

例如

    short oldshort = 700;

    byte byte1= (byte) (oldshort);
    byte byte2= (byte) ((oldshort >> 8) & 0xff);

    short newshort = (short) ((byte2 << 8) + (byte1&0xFF);

        System.out.println(oldshort);
    System.out.println(newshort);

编辑:
所有字节操作和java中的short实际上是以整数形式完成的。所以当你写
+ byte1 时,真正发生的是该字节首先被转换为整数(符号 - 它仍将具有相同的值,但现在有更多的位。然后我们可以屏蔽底部的8位以从短路中获得原始的8位 - 没有符号。

All operations on bytes and shorts in java are actually done as integers. So when you write +byte1, what is really happening is that the byte is first cast to an integer (sign-extended). It will still have the same value, but now has more bits. We can then mask off the bottom 8 bits to get the original 8-bits from the short - without the sign.

E.g. short =511 = 0x01FE
     // lots of 0x000's because the operations are done on 32-bit int's
     byte1 = (0x000001FE & 0x000000FF) = (0x01FE & 0xFF) = 0xFE = (byte)-2
     byte2 = 0x1

     newShort = (byte2 << 8) + (byte1 & 0xFF)
              = (0x1 << 8) + (0xFE & 0xFF)
            // since the ops are performed as int's
              = (0x00000001 << 8) + (0xFFFFFFFE & 0x000000FF)
            // 0xFFFFFFFE = -2 
              = (0x00000100) + (0x000000FE)
              = 0x000001FE
              = 511

这篇关于在Java中从short转换为byte,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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