當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


p5.js byte()用法及代碼示例

p5.j​​s中的byte()函數用於將數字,數字值或布爾值的給定字符串轉換為其字節表示形式。該字節數隻能是-128到127之間的整數。超出範圍的值將轉換為其相應的字節表示形式。

用法:

byte(Value)

參數:該函數接受單個參數Value,該參數將轉換為其字節表示形式。該值可以是整數,浮點數,字符串,布爾值,負值或正值以及值數組。


返回值:它返回轉換後的字節表示形式。

以下示例程序旨在說明p5.js中的byte()函數:

示例1:本示例使用byte()函數將輸入元素轉換為其字節表示形式。

function setup() {  
   
    // Creating Canvas size 
    createCanvas(600, 230);  
}  
   
function draw() {  
       
    // Set the background color  
    background(220);  
     
    // Initializing some values 
    let Value1 = 12; 
    let Value2 = 12.5; 
    let Value3 = -7.9; 
    let Value4 = -6;  
    let Value5 = "6"; 
    let Value6 = 0; 
     
    // Calling to boolean() function. 
    let A = byte(Value1); 
    let B = byte(Value2); 
    let C = byte(Value3); 
    let D = byte(Value4); 
    let E = byte(Value5); 
    let F = byte(Value6); 
       
    // Set the size of text  
    textSize(16);  
       
    // Set the text color  
    fill(color('red'));  
     
    // Getting byte representation 
    text("Byte representation of value 12 is: " + A, 50, 30); 
    text("Byte representation of value 12.5 is: " + B, 50, 60); 
    text("Byte representation of value -7.9 is: " + C, 50, 90); 
    text("Byte representation of value -6 is: " + D, 50, 110); 
    text("Byte representation of string '6' is: " + E, 50, 140); 
    text("Byte representation of string 0 is: " + F, 50, 170); 
} 

輸出:

示例2:本示例使用byte()函數將輸入元素轉換為其字節表示形式。

function setup() {  
   
    // Creating Canvas size 
    createCanvas(600, 140);  
}  
   
function draw() {  
       
    // Set the background color  
    background(220);  
     
    // Initializing some values 
    let Value1 = true; 
    let Value2 = false; 
    let Value3 = "Geeks"; 
    let Value4 = [12, 3.6, -9.8, true, false]; 
     
    // Calling to byte() function. 
    let A = byte(Value1); 
    let B = byte(Value2); 
    let C = byte(Value3); 
    let D = byte(Value4); 
       
    // Set the size of text  
    textSize(16);  
       
    // Set the text color  
    fill(color('red'));  
     
    // Getting byte representation 
    text("Byte representation of value 'true' is: " + A, 50, 30); 
    text("Byte representation of value 'false' is: " + B, 50, 60); 
    text("Byte representation of value 'Geeks' is: " + C, 50, 90); 
    text("Byte representation of array of values are: " + D, 50, 110); 
}    

輸出:

注意:從上麵的示例中可以看出,如果參數是任何小數值,則其輸出將是其整數等效值,即,其範圍和字符串之間的整數應為數字,否則它將給出輸出NaN,而不是數字。

參考: https://p5js.org/reference/#/p5/byte



相關用法


注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 p5.js | byte() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。