您好我正在创建一个方法,将采取一个数字并打印它与其二进制表示.问题是我的方法打印所有0的任何正数,所有1的任何负数
private static void display( int number ){
System.out.print(number + "\t");
int mask = 1 << 31;
for(int i=1; i<=32; i++) {
if( (mask & number) != 0 )
System.out.print(1);
else
System.out.print(0);
if( (i % 4) == 0 )
System.out.print(" ");
}
}
Run Code Online (Sandbox Code Playgroud)
我知道了:这有效:
/**
* prints the 32-bit binary representation of a number
* @param number the number to print
*/
private static void display( int number ){
//display number and a tab
System.out.print(number + "\t");
//shift number 31 …Run Code Online (Sandbox Code Playgroud) 我试图获得a的高4位Byte.
那是我到目前为止的尝试:
function Upper4Bits(const X : Byte): Byte;
type
BS = set of 0..7;
var
K : Byte; Q: BS;
begin
Q := [];
for K := 0 to 3 do {is it right? upper?}
{what i need here?}
Include(Q, {what i put here});
Upper4Bits := Byte(Q)
end;
Run Code Online (Sandbox Code Playgroud)
提前致谢.
为什么64位变量在真正的位进入第31位并且进一步变得更加明显?在第32位它返回一个非常大的值然后重置.
#include <iostream>
using namespace std;
int a[65];
int main()
{
a[0]=1;
for(int i=0;i<=63;++i)
{
for(int k=7;k>=0;--k)
{
for(int j=7;j>=0;--j)
cout<<a[k*8+j];
cout<<' ';
}
cout<<'=';
cout<<(unsigned long long)(1<<i);
cout<<'\n';
a[i]=0;
a[i+1]=1;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud) 如何将整数转换为位表示?
例如,以位表示的9号表示为:10011
例如,要将位序列转换为int表示形式,可以执行以下操作:
$bits_sq = array(1,0,0,1,1);
function convert_bits_to_int($bits_sq){
$sum = 0;
for($i=0; $i < count($bits_sq); $i++){
$sum = $sum + $bits_sq[$i] * pow(-2, $i);
}
print $sum; // equals to 9
}
Run Code Online (Sandbox Code Playgroud)
但是我想反过来。
编辑:不要误用二进制位,这不是双重的,而上面有答案