无符号 byte java_我们能用Java做无符号字节吗?
原語是用Java簽名的,這與它們在內存/傳輸中的表示方式無關-字節僅為8位,是否將其解釋為有符號范圍取決于您。沒有魔法標志可以說“這是簽名的”或“這是未簽名的”。
在對原語進行簽名時,Java編譯器將阻止您將大于+127的值分配給一個字節(或低于-128)。但是,沒有什么可以阻止您為了實現這一點而降低int(或Short):int?i?=?200;?//?0000?0000?0000?0000?0000?0000?1100?1000?(200)byte?b?=?(byte)?200;
//?1100?1000?(-56?by?Java?specification,?200?by?convention)/*
*?Will?print?a?negative?int?-56?because?upcasting?byte?to?int?does
*?so?called?"sign?extension"?which?yields?those?bits:
*?1111?1111?1111?1111?1111?1111?1100?1000?(-56)
*
*?But?you?could?still?choose?to?interpret?this?as?+200.
*/System.out.println(b);?//?"-56"/*
*?Will?print?a?positive?int?200?because?bitwise?AND?with?0xFF?will
*?zero?all?the?24?most?significant?bits?that:
*?a)?were?added?during?upcasting?to?int?which?took?place?silently
*????just?before?evaluating?the?bitwise?AND?operator.
*????So?the?`b?&?0xFF`?is?equivalent?with?`((int)?b)?&?0xFF`.
*?b)?were?set?to?1s?because?of?"sign?extension"?during?the?upcasting
*
*?1111?1111?1111?1111?1111?1111?1100?1000?(the?int)
*?&
*?0000?0000?0000?0000?0000?0000?1111?1111?(the?0xFF)
*?=======================================
*?0000?0000?0000?0000?0000?0000?1100?1000?(200)
*/System.out.println(b?&?0xFF);?//?"200"/*
*?You?would?typically?do?this?*within*?the?method?that?expected?an
*?unsigned?byte?and?the?advantage?is?you?apply?`0xFF`?only?once
*?and?than?you?use?the?`unsignedByte`?variable?in?all?your?bitwise
*?operations.
*
*?You?could?use?any?integer?type?longer?than?`byte`?for?the?`unsignedByte`?variable,
*?i.e.?`short`,?`int`,?`long`?and?even?`char`,?but?during?bitwise?operations
*?it?would?get?casted?to?`int`?anyway.
*/void?printUnsignedByte(byte?b)?{
int?unsignedByte?=?b?&?0xFF;
System.out.println(unsignedByte);?//?"200"}
總結
以上是生活随笔為你收集整理的无符号 byte java_我们能用Java做无符号字节吗?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java调用方法的变量_JAVA类的方法
- 下一篇: java猜数字游戏应用程序_猜数字游戏的