2015-06-10 52 views
2

我再次遇到錯誤的數據類型。這是一個arduino項目。我有個char數組。最後9個字符是rgb,我把它們看成三聯體。所以000255000.數據類型混亂,需要char數組中的整數

我需要通過那些功能,但爲整數,如0,255,0。我很確定,如果000變成0,但我需要045變成45

我試圖投它們,如:

blue = (int)message[11]; 
blue += (int)message[12]; 
blue += (int)message[13]; 

這沒有奏效。然而,我可以將它們投射到絃樂器上,然後我嘗試了:是的,我知道這不是一個好主意,但它值得一試。

char tempBlue[4]; 
blue.toCharArray(tempGreen, sizeof(tempGreen)); 
iBlue = atoi(tempGreen); 

這也沒有奏效。

我失去了如何做到這一點。我不知道如何(如果可以的話)連接整數,或者我會試着這樣做。

編輯------

我問的是錯誤的問題。我應該以相反的方式做這件事。先連接到整數?我把它們當作角色開始。

+0

您可以 「拼接」 兩個整數很簡單,如果第二個是小於10:只計算10 * A + B. –

+0

'blue.toCharArray(tempGreen,的sizeof(tempGreen));' - 你肯定這是C? – szczurcio

+0

@LeeDanielCrocker - 呃,我剛剛看到你的帖子。它慢跑着我的大腦。我知道每個數字只有0-5。因此,int combined =((100 * first)+(10 * second)+ third);是我所需要的。我正在讓它變得複雜。男人,我覺得很愚蠢。 – TheEditor

回答

1

每個字符轉換爲其對應INT請執行下列操作

int first = message[11] - '0'; 
int second= message[12] - '0'; 
int third = message[13] - '0'; 

要明白爲什麼這個工程,你可以點擊這裏:Why does subtracting '0' in C result in the number that the char is representing?

要連接整型,你可以使用此功能

unsigned concatenate(unsigned x, unsigned y) { 
    unsigned pow = 10; 
    while(y >= pow) 
     pow *= 10; 
    return x * pow + y;   
} 

我沒寫這個函數,它是通過@TBohne書面原本here

+0

好吧,我會嘗試。那我怎麼連接呢? – TheEditor

+0

@TheEditor看到我的原始答案,我編輯它來回答你的後續問題 –

+0

好吧,完美地轉換它們,我學到了一些東西。至於連接,我甚至必須這樣做嗎?我會像這樣使用它們:colorWipe(strip.Color(255,0,0),50);有沒有一種更好的方式來從單個整數中獲得255以外的連接?儘管構建每個三元組可以讓我沿途消除前導零。這裏最好的方法是什麼? – TheEditor

1

我一起去:

char *partMessage = (char*)malloc(4); 
partMessage[3] = '\0'; 
strncpy(partMessage, message + 11, 3); 
result = (int)strtol(partMessage, NULL, 10); 
free(partMessage); 
+0

用以前的有用步驟編輯它。 –

+0

已修復。謝謝@chux。 –

0

你可以嘗試這樣的事情

#include <stdio.h> 

int main() 
{ 
    // example 
    char message[] = { "000255000" }; 
    int r=0, g=0, b=0; 

    // make sure right number of values have been read 
    if (sscanf(message, "%03d%03d%03d", &r, &g, &b) == 3) 
    { 
    printf("R:%d, G:%d, B:%d\n", r,g,b); 
    } 
    else 
    { 
    fprintf(stderr, "failed to parse\n"); 
    } 
} 

的sscanf將跳過任何白色空間,所以即使是像message[] = " 000 255 000 ";字符串將工作。

0

只要做手動轉換:

int convert_digits(char *cp, int count) { 
    int result = 0; 
    for (int i = 0; i < count; i += 1) { 
     result *= 10; 
     result += (cp[i] - '0'); 
    } 
    return result; 
} 

char *input = "000045255"; 

int main(int ac, char *av[]) { 
    printf("r=%d g=%d, b=%d\n", 
     convert_digits(cp, 3), 
     convert_digits(cp+3, 3), 
     convert_digits(cp+6, 3)); 
} 
0

字符串轉換爲一個數字,然後數值剝皮及關一次3位數字。

const char *s = "000255000"; 
char *endptr; 
unsigned long num = strtoul(s, &endptr, 10); 

// add error checking on errno, num, endptr) here if desired. 

blue = num%1000; 
num /= 1000; 
green = num%1000; 
num /= 1000; 
red = num%1000; 

// Could add check to insure r,g,b <= 255.