注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

姑射道人的博客

博客新地址:nixuchen.com

 
 
 

日志

 
 

Converting Between Signed and Unsigned Data Types  

2013-12-17 14:43:26|  分类: java |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
Sometimes sticking to the signed part of a data type’s range isn’t possible. When we’re
working with unsigned bytes, we can store any number from 0 to 255. However, Java
will normally only let us store numbers in the range of -128 to 127, and 255 is definitely outside of that range. While we can’t write code that says byteb=255;, there is
a way to fool Java into interpreting the number as a signed byte.
Let’s  take  a  look  at  the  binary  value  for  255:  in  binary,  we  would  represent  this
number as 11111111. We just need to find a way of telling Java to put these bits into
the byte. It turns out that we can do this if we use Java’s bit masking to mask off the
last eight bits of the number 255 as follows:
byteb=(byte)(255&0xff);
This works because Java will interpret the number literal of 255 as being a 32-bit
integer, which is big enough to hold the number 255. However, once we’ve assigned
255 to the byte, Java will actually see this byte as -1 instead of as 255, because to
Java  this  byte  is  signed,  and  it  will  interpret  the  value  using  two’s  complement.
a
However, OpenGL or anywhere else expecting unsigned numbers will see the byte as
255.
To read the value back in Java, we can’t just read it directly because Java sees it as
-1. Instead, we need to use a larger Java data type to hold the result. For example,
we could do the conversion with the following code:
shorts=(short)(b&0xff);
We can’t just use shorts=b;because Java will do sign extensionand our short will
still be -1. By telling Java to mask off the last eight bits, we implicitly convert to an
integer,  and  then  Java  will  correctly  interpret  the  last  eight  bits  of  that  integer  as
255. Our short will then be set to 255, as we expected.
a. http://en.wikipedia.org/wiki/Two's_complement
  评论这张
 
阅读(349)| 评论(0)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017