O'Reilly logo

VBScript in a Nutshell, 2nd Edition by Ron Petrusha, Matt Childs, Paul Lomax

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Name

CByte Function

Syntax

CByte(expression)
expression

Use: Required

Data Type: Numeric or String

A string or numeric expression that evaluates between 0 and 255.

Return Value

expression converted to a type of Byte.

Description

Converts expression to a Byte data type. The Byte type is the smallest data storage device in VBScript. Being only one byte in length, it can store unsigned numbers between 0 and 255.

Rules at a Glance

  • If expression is a string, the string must be capable of being treated as a number.

  • If expression evaluates to less than 0 or more than 255, an overflow error is generated.

  • If expression isn’t a whole number, CByte rounds the number prior to conversion.

Example

If IsNumeric(sMyNumber) Then
    If val(sMyNumber) >= 0 and val(sMyNumber) <= 255 Then
        BytMyNumber = Cbyte(sMyNumber)
    End If
End If

Programming Tips and Gotchas

  • Check that the value you pass to CByte is neither negative nor greater than 255.

  • Use IsNumeric to insure the value passed to CByte can be converted to a numeric expression.

  • When using CByte to convert floating-point numbers, fractional values up to but not including 0.5 are rounded down, while values greater than 0.5 are rounded up. Values of 0.5 are rounded to the nearest even number (i.e., they use the Banker’s Rounding Algorithm).

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required