[ create a new paste ] login | about

Link: http://codepad.org/KwNQEQ7Z    [ raw code | output | fork ]

AaronMiller - C, pasted on Sep 24:
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>

#if __GNUC__ || __clang__
# ifndef __forceinline
#  define __forceinline __inline __attribute__((always_inline))
# endif
#endif

// sex = Sign EXtend
__forceinline unsigned int sex(int x) { return x >> (sizeof(x)*8 - 1); }
// clamp_u8 = CLAMP to Unsigned 8-bit
__forceinline unsigned int clamp_u8(int x) {
    return (~sex(x - 1)) & (255 + ((x - 255) & sex(x - 255))); 
}

void test_sex(int x) { printf("sex(%i) -> 0x%.8X\n", x, sex(x)); }
void test_clamp_u8(int x) { printf("clamp_u8(%i) -> 0x%.8X\n", x, clamp_u8(x)); }

int main() {
    test_sex(-1); test_sex(0); test_sex(1); test_sex(-4523563); test_sex(4523563);
    test_clamp_u8(-256);
    test_clamp_u8(-128);
    test_clamp_u8(-175);
    test_clamp_u8(-1);
    test_clamp_u8(0);
    test_clamp_u8(25);
    test_clamp_u8(127);
    test_clamp_u8(175);
    test_clamp_u8(255);
    test_clamp_u8(256);
    test_clamp_u8(1024);
    return EXIT_SUCCESS;
}


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
sex(-1) -> 0xFFFFFFFF
sex(0) -> 0x00000000
sex(1) -> 0x00000000
sex(-4523563) -> 0xFFFFFFFF
sex(4523563) -> 0x00000000
clamp_u8(-256) -> 0x00000000
clamp_u8(-128) -> 0x00000000
clamp_u8(-175) -> 0x00000000
clamp_u8(-1) -> 0x00000000
clamp_u8(0) -> 0x00000000
clamp_u8(25) -> 0x00000019
clamp_u8(127) -> 0x0000007F
clamp_u8(175) -> 0x000000AF
clamp_u8(255) -> 0x000000FF
clamp_u8(256) -> 0x000000FF
clamp_u8(1024) -> 0x000000FF


Create a new paste based on this one


Comments: