简单但难以转换的价值观。 [英] Simple but difficult conversion values.

查看:59
本文介绍了简单但难以转换的价值观。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将价值直接转移到2间客房的最佳方法是什么?



char a [2];



我想把'0xff00'的值移到这个房间,如下所示但是失败了。



a [0] ='0xff';

a [1] ='0x00'; //或者[1] = 0;



我想知道将十六进制值直接插入任何其他字符存储空间的方法....



我的尝试:



浪费了4个多小时来解决这个问题但是失败。

What is the best way to move value directly to 2 char rooms?

char a[2];

I want to move the value of '0xff00' to this room like as follows but failed.

a[0] = '0xff';
a[1] = '0x00'; // or a[1] = 0;

I want to know the method to insert directly hex value to any other char memory spaces....

What I have tried:

More than 4 hours wasted to solve this problem but failed.

推荐答案

这里存在许多问题:字符数量在字节边界上对齐,但整数不对齐 - 它们在字边界上对齐。 br />
这意味着基于char的值的地址可以是0,1,2,3,4,5,6 ......但是整数的地址只能是0,4, 8,16,...

其原因与处理器的工作方式以及内存的实际处理方式有关。试图将整数值填充到基于字符的地址中很容易导致其他内存损坏,或错误的值进入错误的位置。

如果不是这样,那么你可以去:

There are a number of problems here: char quantities are aligned on byte boundaries, but integers aren't - they are aligned on word boundaries.
What that means is that the address of a char based value can be 0, 1, 2, 3, 4, 5, 6 ... but the address of an integer can only be 0, 4, 8, 16, ...
The reason for this has to do with how the processor works and how memory is actually addressed. Trying to "stuff" an integer value into a char based address can easily end up with other memory getting corrupted, or the wrong values going into the wrong locations.
If that wasn't the case, you could just go:
int *pi = (int *)a;
*pi = 0xff00;

但是......即使这样做起因为地址很好也会有另一个问题:Endianness。 PC处理器是所谓的Little Endian,这意味着它将值的最低有效字节存储在最低阶地址中:因此该值将以错误的方式进行,在[0]中为0x00,并且[1]中的0xFF。 (即使不是这样,因为现在大多数处理器都是32位或64位,很少有16位,它仍然无法在正确的位置获得正确的值。



但是......你可以这样做:

But...even if that worked because the addresses were fine there would be another problem: Endianness. The PC processor is what is called "Little Endian", which means that it stores the least significant byte of a value in the lowest order address: so the value would go in the wrong way round, with 0x00 in a[0], and 0xFF in a[1]. (Even if it wasn't, since most processors are 32 or 64 bit these days with very few being 16 bit, it would still not get the right values in the right locations.

But...you can do it:

unsigned char a[2];
int i = 0xFF00;
a[0] = (unsigned char) (i >> 8);
a[1] = (unsigned char) (i & 0xFF);

这可能不是一件有用的事情!:笑:

It's just probably not a useful thing to do! :laugh:


这篇关于简单但难以转换的价值观。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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