Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unsigned tinyint in php?

Tags:

types

php

integer

I'm working on a class to manipulate html hex color codes in php. Internally, the class treats RGB values as decimals. When I'm adding or subtracting, I never want the value to exceed 255 nor 'subceed' zero.

If course, I can do something piecemeal like

if ( $val >  255 ) {
    $val = 255;
} 
if ( $val < 0 ) {
    $val = 0;
}

But that's verbose :P

Is there a clever, one-linish way I can get the value to stay between 0 and 255?

like image 697
user151841 Avatar asked Apr 29 '10 15:04

user151841


People also ask

Is Tinyint signed or unsigned?

SIGNED, UNSIGNED and ZEROFILL For example, a TINYINT SIGNED can range from -128 to 127. If UNSIGNED is specified, no portion of the numeric type is reserved for the sign, so for integer types range can be larger. For example, a TINYINT UNSIGNED can range from 0 to 255.

What is Tinyint PHP?

If unsigned, the allowable range is from 0 to 4294967295. You can specify a width of up to 11 digits. TINYINT − A very small integer that can be signed or unsigned. If signed, the allowable range is from -128 to 127. If unsigned, the allowable range is from 0 to 255.

What is TINYINT Data Type in MySQL?

TINYINT is a very small integer. The minimum and maximum SIGNED values are -128 and 127 respectively, while for UNSIGNED values TINYINT range is from 0 to 255. TINYINT uses 1 byte per row.

What is Mediumint?

A medium-sized integer. The signed range is -8388608 to 8388607. The unsigned range is 0 to 16777215. ZEROFILL pads the integer with zeroes and assumes UNSIGNED (even if UNSIGNED is not specified). INT3 is a synonym for MEDIUMINT .


2 Answers

You could possibly say something like: $val = max(0, min(255, $val));

like image 91
Narcissus Avatar answered Oct 28 '22 23:10

Narcissus


Using the bitwise OR operator would work

if(($num | 255) === 255) { /* ... */ }

Example:

foreach (range(-1000, 1000) as $num) {
    if(($num | 255) === 255) {
        echo "$num, ";
    };
}

would print out all the numbers from 0 to 255.

like image 21
Gordon Avatar answered Oct 28 '22 23:10

Gordon