添加4个字节值会导致溢出异常

时间:2018-01-29 21:16:26

标签: vb.net visual-studio-2017

以下代码引发System.OverflowException

    Dim b1 As Byte = 13
    Dim b2 As Byte = 26
    Dim b3 As Byte = 125
    Dim b4 As Byte = 225

    Dim i As Integer = (b1 + b2 + b3 + b4) \ 2

为什么会这样?

1 个答案:

答案 0 :(得分:5)

在将值分配给变量之前,值不会转换为Integer。这意味着在\ 2部分之前,包括Byte部分仍然属于Integer类型。

为了完成这项工作,您必须至少将第一个变量转换为Dim i As Integer = (CType(b1, Integer) + b2 + b3 + b4) \ 2 ,以便可以添加其他数字并超过255.

Dim i As Integer = (CType(b1, Integer) + b2 * b3 + b4) \ 2

在线测试: https://dotnetfiddle.net/Lxmx2S

请注意,由于这会考虑数学运算的顺序,因此必须转换在其他类型之前计算的太小类型的所有实例。例如,如果您将操作更改为:

b2 * b3

它也会引发错误,因为b1 + b2Dim i As Integer = (CType(b1, Integer) + CType(b2, Integer) * b3 + b4) \ 2 之前计算,因此您必须将其更改为:

    while(1){ //loop the child

         bzero(buffer, 256);
         n = recv(newsockfd, buffer, 255,0);
        printf("read %d ",n);
        printf("pid %d\n",getpid());
         if (n < 0) error("ERROR reading from socket");{
             printf("Here is the message: %s\n", buffer);

        }
        if (strcmp(buffer,"quit") == 0){
            printf("Disconnect from %s:%d\n",str,portno);
            exit(EXIT_SUCCESS);
        }else{  
             n = send(newsockfd, "message received\n", 19,0);
             if (n < 0) error("ERROR writing to socket");
             bzero(buffer, 256);

            }
     }
   }else{ //parent 
    recv(newsockfd,gepid,10,0); //get the child pid
    endID = waitpid(gepid,&status,WNOHANG|WUNTRACED); //get the exit code gepid want to be the child pid 
    if (endID==-1){
         error("waitpid");
    }else if (endID==0){
        printf("Child still running!");
     }else if(endID==childpid){
        check_child_exit(status);
    }       
  } 
}   
    close(newsockfd);

       return 0;
}