添加到未签名的字符 [英] Adding to an unsigned char

查看:64
本文介绍了添加到未签名的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是特定于系统的,但我想知道哪些系统也不同(它的字节序).

我有一个

This is probably system specific but I would like to know what systems are different also (its endian stuff).

I have a

unsigned char buffer[4]



我已将所有字节初始化为0
0x00

我偶尔会添加第0个元素



I have initialized all bytes to have 0
0x00

I am adding to the 0 th element occasionally

buffer[0] += someSmallAddValueThatIsAnInt; 



当值太大而溢出时会发生什么?

崩溃了吗?
buffer [1]获取LS数据,buffer [0]获取MS?
buffer [1]获取MS数据,buffer [0]获取LS?
buffer [-1]获取LS数据,buffer [0]获取MS数据?
buffer [-1]获取MS数据,buffer [0]获取LS数据?

谢谢.



At the point that the value is too large and overflows what will happen?

Crash?
buffer[1] gets LS data and buffer[0] gets MS?
buffer[1] gets MS data and buffer[0] gets LS?
buffer[-1] gets LS data and buffer[0] gets MS data?
buffer[-1] gets MS data and buffer[0] gets LS data?

Thank you.

推荐答案

buffer[0]值设置为
It happens that buffer[0] value is set to
(buffer[0] + thatValueWithThatSillyName ) % 256


(即结果被截断以适合一个字节).
没什么.
:)


(i.e. the result is truncated to fit into a byte).
Nothing else.
:)


人们希望加法不会破坏你的邻居.现在,如果您真的只是想看看如果溢出的话会发生什么,这个小片段会导致溢出.

One would hope that doing addition doesn''t corrupt your neighbors. Now if you really just want to see what would happen if it did over flow this little snippet forces an overflow.

unsigned char test[10] = {0};
    int * testptr= NULL;
    testptr = (int*)&test[5];

    test[5] = 254;
    test[5] = test[5] + 3;
    *testptr = 300;



如您所料,当您将3加到254时,它会被截断.

通过在执行赋值操作时将对im编辑值的引用转换为int,假设我在该内存位置有4字节的空间.不出所料,上述值渗入测试[6].取决于系统,它很可能渗入test [4]而不是

SH



As expected when the you add 3 to 254 it truncates.

By casting a reference to the value im editing as an int when you do the assignment it is assuming I have a 4 Byte space at that memory location. As expected the value above bleeds over into test[6]. Depending on the system it could very well bleed over into test[4] instead

SH


我在VS2010上对此进行了测试.

buffer [0]获取LS,MS进入位存储桶.查看内存调试窗口,我可以看到内存已设置为此...

cc cc cc cc 02 00 00 00 cc cc cc cc

当我使用以下代码时.我移回内存以显示-1值.

I tested this with VS2010.

buffer[0] gets LS and MS goes to the bit bucket. Looking at the memory debug window I was able to see that the memory was set to this...

cc cc cc cc 02 00 00 00 cc cc cc cc

when I used this following code. I moved back in memory to show the -1 value.

unsigned char buffer[4];
buffer[0] = 0;
buffer[1] = 0;
buffer[2] = 0;
buffer[3] = 0;
buffer[0] = 255;
buffer[0] += 3;


这篇关于添加到未签名的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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