答案假定未签名,为您的具体作业修改
如果在第三个或第四个字节上设置了任何位,那么您无法适应它,所以您的老师想要这样的东西:
//check the third byte for bits //check the 4th byte for bits
retbool = (((unsigned char)(x >> 16) & 0xFF) | ((unsigned char)(x >> 24) & 0xFF)));
如果设置了这些字节中的任何位,则您无法将正方形放入 32 位 int 中。如果问题是关于 unsigned int 32 这将是结束,但是由于 0xFFFF * 0xFFFF 大于 max signed int,所以对于符号位,您还必须对第二个字节进行一些检查。
因为你永远不可能真的有一个负平方,所以无符号版本应该是一个替代答案,但我没有写这个作业。
编辑(如果位模式是唯一的,您必须屏蔽...)
#include <stdio.h>
int doesFit(int x);
typedef unsigned char uchar;
typedef unsigned short ushort;
#define MAX_POS_SQUARE 46340
#define MAX_NEG_SQUARE -46340
int main(void) {
int x=MAX_NEG_SQUARE -2;
int fits = -1;
int prevoiusly_fit = 0;
for(;x<MAX_POS_SQUARE+5;x++){
fits = doesFit(x);
if(!fits && prevoiusly_fit){
printf("%d didnt fit and %d did\n",x,x-1);
}
else if(fits && !prevoiusly_fit){
printf("%d fit and %d did not\n",x,x-1);
}
prevoiusly_fit = fits;
}
return 0;
}
int doesFit(int x){
uchar bits_left = 16;
ushort pos_mask = ((0xb5 << 8) | 0x04);
ushort neg_mask = ((0xb5 << 8) | 0x05);
ushort x_16_low = (((-x) & 0xff << 8 ) | (-x) & 0xff); //used in negative case
ushort x_16_high = (-x)>>16; //used in negative case
//Handle the negative case
//printf("0x%04x x: 0x%04x x_16_low: 0x%04x x_16_high:", x, x_16_low, x_16_high);
if(x>>31){
//how can you tell if a value x < -46340
if( (x_16_high & 0xFF) | (x_16_high >>8 & 0xFF)){
//doesnt fit, maybe dont use compliment use ! if accidental promotion occurs
printf("bailing out when x=%d\n", x);
return 0;
}
while(bits_left){
--bits_left;
if(x_16_low & (1 << bits_left)){
if(!(neg_mask & (1 << bits_left))){
return 0;
}
}
else if(!(x_16_low & (1 << bits_left))){
if(neg_mask & (1 << bits_left)){
return 1;
}
}
//high bits matched with max value bits, cant tell yet, keep masking.
}
}
else{ //handle the positive case
//how can you tell if a value x > 46340
if( (x >> 16 & 0xFF) | (x >>24 & 0x7F)){
//doesnt fit, return false
return 0;
}
while(bits_left){
--bits_left;
if(x & (1 << bits_left)){
if(!(pos_mask & (1 << bits_left))){
return 0;
}
}
else if(!(x & (1 << bits_left))){
if(pos_mask & (1 << bits_left)){
return 1;
}
}
//high bits matched with max value bits, cant tell yet, keep masking.
}
}
return 1; //Must be the exact size to fit to get to this return
}
输出:
-46341 适合而 -46342 不适合
46341 不适合,46340 适合
我觉得我只是浪费了我生命中的一个小时来做这些家伙的家庭作业......