# Integer to Byte

## Recommended Posts

I'm working on a grayscale algorithm, and I need to know how to convert an integer to a byte value. How can I do this?

The God of Judgement is not pleased...

##### Share on other sites

I'm working on a grayscale algorithm, and I need to know how to convert an integer to a byte value. How can I do this?

The God of Judgement is not pleased...

##### Share on other sites

A simple type cast might do it:

ByteVar = (byte)IntVar;

Or, if you want to clamp to a byte value:

ByteVar = Utility.ClampToByte(IntVar);

##### Share on other sites

A simple type cast might do it:

ByteVar = (byte)IntVar;

Or, if you want to clamp to a byte value:

ByteVar = Utility.ClampToByte(IntVar);

##### Share on other sites

Thanks.

The God of Judgement is not pleased...

##### Share on other sites

Thanks.

The God of Judgement is not pleased...

##### Share on other sites

• 2 weeks later...
I'm working on a grayscale algorithm, and I need to know how to convert an integer to a byte value. How can I do this?

If you working with colors then proper way is using ColorBgra class. (properties .R, .G, .B, .A)

```ColorBgra srcColor = srcArgs.Surface[x, y];

Byte grayByte = (byte)((double)srcColor.R * 0.299 + (double)srcColor.G * 0.587 + (double)srcColor.B * 0.114);

ColorBgra destColor;
destColor.R = destColor.G = destColor.B = grayByte;
destColor.A = 255;```

In generally you can use divide, modulo and cast operations.

```uint intVal = 0xAABBCCDD;
byte byteR = (byte)((intVal / (256 * 256 * 256)) % 256); // AA
byte byteG = (byte)((intVal / (256 * 256      )) % 256); // BB
byte byteB = (byte)((intVal / (256            )) % 256); // CC
byte byteA = (byte)((intVal                    ) % 256); // DD
```

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×