1

I am new to c programming. As a part of my uni course for network security, I have to design a SSL handshake simulation. I found a sample code online, however i don't understand some parts of the code. Could you please help me with following :

What does (char) 0 do ?? ( send_data is defined as char send_data[1024]; )

send_data[0] = (char) 0;                //Packet Type = hello
send_data[1] = (char) 3;                //Version

EDIT + FOLLOWUP

Folks I know what type casting is.

I understand what casting is But the code I posted is doing nothing. Even though integer 0 is being cast as a character, its not doing anything because when you print it - its a blank - no value.

eg :

#include <stdio.h>
#include <stdlib.h>

int main(){

char test;
int num;

num = 1;
test = (char) num; // this does nothing

printf("num = %d , %c\n",num,num);
printf("test = %d , %c\n",test,test);

    // Isn't this the correct way to do it ?? :

num = 3;
test = '3'; // now this is a character 3

printf("num = %d , %c\n",num,num);
printf("test = %d , %c\n",test,test);

return 0;

}

the output of above code is :

num = 1 , 
test = 1 , 
num = 3 , 
test = 51 , 3

So why is it being done ?? isn't this the right way to do it :- send_data[0] = '0'; send_data[1] = '3';

4

6 回答 6

6

它只是将int0(或 3)转换为char类型。

这可能不是必需的,但可用于删除可能截断的警告。

更好的成语是:

send_data[0] = '\x00';   // Packet Type = hello
send_data[1] = '\x03';   // Version

因为这些都是明确的字符,所以不必担心演员表。

请记住,(char) 0(或'\x00')与不同'0'。前两者为您提供字符代码 0(NULASCII 字符),后者为您提供可打印 0字符的字符代码(字符代码 48 或'\x30'ASCII 字符)。这就是为什么您的打印没有像您预期的那样运行。

您的特定协议是否需要代码点 0 或可打印字符 0 是您尚未明确的事情。如果您真的想模拟 SSLv3,那么正确的值是二进制而不是RFC6101中的可打印值:

enum {
    hello_request(0), client_hello(1), server_hello(2),
    certificate(11), server_key_exchange (12),
    certificate_request(13), server_done(14),
    certificate_verify(15), client_key_exchange(16),
    finished(20), (255)
} HandshakeType;
于 2013-08-20T08:39:52.080 回答
1

它只是将文字符号转换为 char 值。但我认为没有必要。

于 2013-08-20T08:43:00.547 回答
0

它将值转换类型。intchar

于 2013-08-20T08:40:22.237 回答
0
int main() 
{ 
    char ch;
    ch = (char) 0;
    printf("%d\n", ch);   //This will print 0
    printf("%c\n", ch);   //This will print nothing (character whose value is 0 which is NUL)
    ch = (char) 3;
    printf("%d\n", ch);   //This will print 3
    printf("%c\n", ch);   //This will print a character whose value is 3
    return 0;
}

它是将 int 类型转换为 char 类型的类型。

    Its good to create a demo program and test it when you get some doubts while reading.
于 2013-08-20T08:43:11.767 回答
0

这称为type-conversioncasting。当您需要将一种数据类型的实体更改为另一种时,您可以这样做。

在您的示例中,0 和 3(整数)被转换为类型字符。

http://en.wikipedia.org/wiki/Type_conversion

于 2013-08-20T08:42:12.967 回答
0

send_data被定义为一个数组char。但是0and3是整数文字。当整数分配给数组时,它们被强制转换为char. 这意味着send_data [0]将保存 ASCII 值为 0 的字符,即NUL字符。send_data[1]将保存 ASCII 值为 3 的字符,即end of text字符。

于 2013-08-20T08:42:49.413 回答