История изменений
Исправление beastie, (текущая версия) :
Тогда уж:
#include <arpa/inet.h>
#include <stdio.h>
#include <stdint.h>
uint32_t
setbyte(uint32_t in, uint8_t val, unsigned int n)
{
const int bytes = sizeof(uint32_t) / sizeof(uint8_t);
union {
uint32_t l;
uint8_t b[bytes];
} d;
if (n >= bytes)
return in;
d.l = htonl(in);
d.b[bytes - n - 1] = val;
return ntohl(d.l);
}
int
main()
{
printf("0x%.8x\n", setbyte(0x6100, 0x41, 0));
printf("0x%.8x\n", setbyte(0x6100, 0x41, 1));
printf("0x%.8x\n", setbyte(0x6100, 0x41, 2));
printf("0x%.8x\n", setbyte(0x6100, 0x41, 3));
printf("0x%.8x\n", setbyte(0x6100, 0x41, 4)); // shall fail
return 0;
}
0x00006141
0x00004100
0x00416100
0x41006100
0x00006100
Исправление beastie, :
Тогда уж:
#include <arpa/inet.h>
#include <stdio.h>
#include <stdint.h>
uint32_t
setbyte(uint32_t in, uint8_t val, unsigned int n)
{
const int bytes = sizeof(uint32_t) / sizeof(uint8_t);
union {
uint32_t l;
uint8_t b[bytes];
} d;
if (n >= bytes)
return in;
d.l = htonl(in);
d.b[bytes - n - 1] = val;
return ntohl(d.l);
}
int
main()
{
printf("0x%.8x\n", setbyte(0x6100, 0x41, 0));
printf("0x%.8x\n", setbyte(0x6100, 0x41, 1));
printf("0x%.8x\n", setbyte(0x6100, 0x41, 2));
printf("0x%.8x\n", setbyte(0x6100, 0x41, 3));
printf("0x%.8x\n", setbyte(0x6100, 0x41, 4)); // shall fail
return 0;
}
0x00006141
0x00004100
0x00416100
0x41006100
Исходная версия beastie, :
Тогда уж:
#include <arpa/inet.h>
#include <stdio.h>
#include <stdint.h>
uint32_t
setbyte(uint32_t in, uint8_t val, unsigned int n)
{
int i = sizeof(uint32_t) / sizeof(uint8_t) - 1 - n;
union {
uint32_t l;
uint8_t b[4];
} d;
if (i < 0)
return in;
d.l = htonl(in);
d.b[i] = val;
return ntohl(d.l);
}
int
main()
{
printf("0x%.8x\n", setbyte(0x6100, 0x41, 0));
printf("0x%.8x\n", setbyte(0x6100, 0x41, 1));
printf("0x%.8x\n", setbyte(0x6100, 0x41, 2));
printf("0x%.8x\n", setbyte(0x6100, 0x41, 3));
printf("0x%.8x\n", setbyte(0x6100, 0x41, 4)); // shall fail
return 0;
}
0x00006141
0x00004100
0x00416100
0x41006100