将整数转换为char数组(byte' s) [英] Convert integers to char arrays(byte's)

查看:66
本文介绍了将整数转换为char数组(byte' s)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:我可以很容易地做到从字节到整数的操作,但是当前的操作方式似乎效果不佳.

UPDATE: I can do it easily from bytes to integers, but the current way I'm doing it seems to not be working so well.

这是我当前的代码:

static unsigned char* Int32ToBytes(signed int n)
{
    unsigned char bytes[4];
    for(int i = 0;i<4;i++)
        bytes[3-i] = (n & (255 << (i*8))) >> (i*8);
    return bytes;
}

我正在用它来写字节:

fwrite(Int32ToBytes(-1), 1 , 4 , file );

当我希望它输出 FF FF FF FF (带符号整数)时,它输出: FB 9C 8B 28 .

It's outputting: FB 9C 8B 28 when I want it to output FF FF FF FF (signed ints).

有什么想法吗?感谢您的帮助:)

Any ideas? Help is appreciated :)

推荐答案

似乎对我有用 http://ideone.com/o6Llf9

void process(int x)
{
    for(int i = 0;i<4;i++)
    {
        unsigned char res = (x & (255 << (i*8))) >> (i*8);
        printf("%x " ,res);
    }
}

int main()
{
    int n;
    while (scanf("%d",&n)!=EOF) process(n);
    return 0;
}

类似的东西也可以工作

for(int i = 0;i<4;i++)
{
     bytes[3-i] = n & 255
     n = n >> 8
}

这篇关于将整数转换为char数组(byte&#39; s)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆