将byte[]转成int和C中atoi效果不一样

Andy84920 2010-06-01 10:15:16
byte[] b= new byte[4];
b[0] = 0x39;
b[1] = 0x69;
b[2] = (byte)0xcc;
b[3] = 0x55;
int dec_len = bytesToInt(b);
public static int bytesToInt(byte[] b) {
int temp = 0;
int res = 0;
for (int i = 0; i < 4; i++) {
res <<= 8;
temp = b[i]&0xFF;
res |= temp;
}
return res;
}
这样出来的结果是963234901.但在C里用atoi(b)的话是9。难道这个bytesToInt不对?
...全文
130 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
atoi 相当于 Integer.parseInt

呵呵
wcwtitxu 2010-06-01
  • 打赏
  • 举报
回复
public static int atoi(byte[] bytes) {
return Integer.parseInt("0"+ new String(bytes).replaceAll("(?s)\\D.*", ""), 10);
}

public static void main(String[] args) {
System.out.println(
atoi(new byte[] { 0x39, 0x69, (byte)0xcc, 0x55 })
);
}
fei1703 2010-06-01
  • 打赏
  • 举报
回复
Java转化后的结果是对的。
atoi是将字符串转化为整形,并不是你想的功能。
龙四 2010-06-01
  • 打赏
  • 举报
回复
函数说明: atoi()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时('\0‘)才结束转换,并将结果返回。
返回值: 返回转换后的整型数。
Foxswily 2010-06-01
  • 打赏
  • 举报
回复
跟BE/LE有关?是在Linux下吧,试试颠倒高低位再转换
龙四 2010-06-01
  • 打赏
  • 举报
回复
我看了下这几个字符,分别是9i?U,总之后面显示不出来,第一个字符时9,从第二个开始就不知道是什么了,atoi是不是忽略非数字部分呢?

[Quote=引用 5 楼 andy84920 的回复:]

int main()
{
char ss[5] = {0};

ss[0] = 0x39;
ss[1] = 0x69;
ss[2] = 0xCC;
ss[3] = 0x55;
ss[4] = 0;

printf("%d\n", atoi(ss));
}

这个结果就是9
[/Quote]
龙四 2010-06-01
  • 打赏
  • 举报
回复
没错,但字符指针不是byte数组

[Quote=引用 6 楼 andy84920 的回复:]

字符指针就是一个char数组啊。看来楼上没怎么用过C?
[/Quote]
24K純帥 2010-06-01
  • 打赏
  • 举报
回复

public static String bytes2HexString(byte[] b) {
String ret = "";
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[ i ] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
ret += hex.toUpperCase();
}
return ret;
}
Andy84920 2010-06-01
  • 打赏
  • 举报
回复
字符指针就是一个char数组啊。看来楼上没怎么用过C?
Andy84920 2010-06-01
  • 打赏
  • 举报
回复
int main()
{
char ss[5] = {0};

ss[0] = 0x39;
ss[1] = 0x69;
ss[2] = 0xCC;
ss[3] = 0x55;
ss[4] = 0;

printf("%d\n", atoi(ss));
}

这个结果就是9
龙四 2010-06-01
  • 打赏
  • 举报
回复
atoi的参数不是一个字符指针么,你放一个byte数组进去算哪门子事情

atoi的功能应该是
char *value = "12345";
int i = atoi(value);
printf("%d",i);

结果应该是12345
龙四 2010-06-01
  • 打赏
  • 举报
回复
16进制的3969cc55怎么可能是9?!


[Quote=引用 2 楼 andy84920 的回复:]

System.out.println(Integer.parseInt("3969cc55", 16));
结果也是963234901,并不是atoi的结果9
[/Quote]
Andy84920 2010-06-01
  • 打赏
  • 举报
回复
System.out.println(Integer.parseInt("3969cc55", 16));
结果也是963234901,并不是atoi的结果9
龙四 2010-06-01
  • 打赏
  • 举报
回复
直接用Integer.parseInt吧

62,612

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧