有人可以解释这个“端序”功能为我? [英] Can someone explain this "endian-ness" function for me?

查看:88
本文介绍了有人可以解释这个“端序”功能为我?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写程序以确定计算机是大端还是小端。

Write a program to determine whether a computer is big-endian or little-endian.

bool endianness() {
     int i = 1;
     char *ptr;
     ptr  = (char*) &i;
     return (*ptr);
}

所以我有上面的函数。我真的不明白。 ptr =(char *)& i,我认为这意味着指向一个字符的指针,我在坐在地址,所以如果一个int是4字节,说ABCD,我们谈论A或D当你调用char *对吗?为什么?

So I have the above function. I don't really get it. ptr = (char*) &i, which I think means a pointer to a character at address of where i is sitting, so if an int is 4 bytes, say ABCD, are we talking about A or D when you call char* on that? and why?

有人会更详细地解释一下吗?谢谢。

Would some one please explain this in more detail? Thanks.

因此,具体来说,ptr =(char *)&i;

So specifically, ptr = (char*) &i; when you cast it to char*, what part of &i do I get?

推荐答案

如果你有一个小端字符串架构, i 在内存中将是这样(十六进制):

If you have a little-endian architecture, i will look like this in memory (in hex):

01 00 00 00
^

如果您有大端架构, c $ c> i 在内存中将是这样(十六进制):

If you have a big-endian architecture, i will look like this in memory (in hex):

00 00 00 01
^

投射到 char * 给你一个指向int的第一个字节的指针(我用 ^ 指向),所以 00 如果您使用的是小端字体架构,则<>

The cast to char* gives you a pointer to the first byte of the int (to which I have pointed with a ^), so the value pointed to by the char* will be 01 if you are on a little-endian architecture and 00 if you are on a big-endian architecture.

当您返回该值时, 0 将转换为 false 1 转换为 true 。所以,如果你有一个little-endian架构,这个函数将返回 true ,如果你有一个big-endian架构,它会返回 false

When you return that value, 0 is converted to false and 1 is converted to true. So, if you have a little-endian architecture, this function will return true and if you have a big-endian architecture, it will return false.

这篇关于有人可以解释这个“端序”功能为我?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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