将带有中间转换的char *的缓冲区设置为int * [英] Setting a buffer of char* with intermediate casting to int*

查看:119
本文介绍了将带有中间转换的char *的缓冲区设置为int *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法完全了解我在这里阅读的结果:将一个int指针转换为一个char ptr,反之亦然

I could not fully understand the consequences of what I read here: Casting an int pointer to a char ptr and vice versa

总之,这是否有效?

set4Bytes(unsigned char* buffer) {
  const uint32_t MASK = 0xffffffff;
  if ((uintmax_t)buffer % 4) {//misaligned
     for (int i = 0; i < 4; i++) {
       buffer[i] = 0xff;
     } 
  } else {//4-byte alignment
    *((uint32_t*) buffer) = MASK;
  }

}

>

有一个很长的讨论(它在评论中,神秘地被删除)关于应该投射指针以检查对齐方式的类型。主题现在处理此处

推荐答案

如果您在所有 4字节。如果字节顺序重要,那么这种转换是不安全的。
因为当你使用整数来填充 4 Bytes 时,它会填充 4 Bytes ,但顺序取决于endianness

This conversion is safe if you are filling same value in all 4 bytes. If byte order matters then this conversion is not safe. Because when you use integer to fill 4 Bytes at a time it will fill 4 Bytes but order depends on the endianness.

这篇关于将带有中间转换的char *的缓冲区设置为int *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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