Skip to content

Commit 5d8a8f9

Browse files
Raimo33Claudio Raimondi
authored andcommitted
Optimize write_be and read_be
1 parent c351b78 commit 5d8a8f9

File tree

1 file changed

+20
-24
lines changed

1 file changed

+20
-24
lines changed

src/util.h

Lines changed: 20 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -419,42 +419,38 @@ static SECP256K1_INLINE int secp256k1_ctz64_var(uint64_t x) {
419419

420420
/* Read a uint32_t in big endian */
421421
SECP256K1_INLINE static uint32_t secp256k1_read_be32(const unsigned char* p) {
422-
return (uint32_t)p[0] << 24 |
423-
(uint32_t)p[1] << 16 |
424-
(uint32_t)p[2] << 8 |
425-
(uint32_t)p[3];
422+
uint32_t x;
423+
memcpy(&x, p, sizeof(x));
424+
#ifdef LITTLE_ENDIAN
425+
x = BYTESWAP_32(x);
426+
#endif
427+
return x;
426428
}
427429

428430
/* Write a uint32_t in big endian */
429431
SECP256K1_INLINE static void secp256k1_write_be32(unsigned char* p, uint32_t x) {
430-
p[3] = x;
431-
p[2] = x >> 8;
432-
p[1] = x >> 16;
433-
p[0] = x >> 24;
432+
#ifdef LITTLE_ENDIAN
433+
x = BYTESWAP_32(x);
434+
#endif
435+
memcpy(p, &x, sizeof(x));
434436
}
435437

436438
/* Read a uint64_t in big endian */
437439
SECP256K1_INLINE static uint64_t secp256k1_read_be64(const unsigned char* p) {
438-
return (uint64_t)p[0] << 56 |
439-
(uint64_t)p[1] << 48 |
440-
(uint64_t)p[2] << 40 |
441-
(uint64_t)p[3] << 32 |
442-
(uint64_t)p[4] << 24 |
443-
(uint64_t)p[5] << 16 |
444-
(uint64_t)p[6] << 8 |
445-
(uint64_t)p[7];
440+
uint64_t x;
441+
memcpy(&x, p, sizeof(x));
442+
#ifdef LITTLE_ENDIAN
443+
x = BYTESWAP_64(x);
444+
#endif
445+
return x;
446446
}
447447

448448
/* Write a uint64_t in big endian */
449449
SECP256K1_INLINE static void secp256k1_write_be64(unsigned char* p, uint64_t x) {
450-
p[7] = x;
451-
p[6] = x >> 8;
452-
p[5] = x >> 16;
453-
p[4] = x >> 24;
454-
p[3] = x >> 32;
455-
p[2] = x >> 40;
456-
p[1] = x >> 48;
457-
p[0] = x >> 56;
450+
#ifdef LITTLE_ENDIAN
451+
x = BYTESWAP_64(x);
452+
#endif
453+
memcpy(p, &x, sizeof(x));
458454
}
459455

460456
/* Rotate a uint32_t to the right. */

0 commit comments

Comments
 (0)