Why you should not trust Chat-gpt

as a developer, as anybody actually…

Lorenzo Piombini
4 min readJun 26, 2024

i was studying bitwise operation in C language, and i decided to brush up the conversion between base 2 and base 10, this is the program :

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

int convert_to_base10(char *base2, unsigned int size){
int i = 0;
int j = 0;
int result = 0;
for(i = size - 1 ; i >= 0 ; i-- )
result += (int)(base2[i] - '0') *(int)pow(2,j), j++;

return result;

}

int main (){

int size = 33;// making room to '\n'
char buffer[size];

printf("give me a binary number: ");
fgets(buffer, size, stdin);

char nl = '\n';
buffer[strcspn(buffer, &nl)] = 0;

int result = convert_to_base10(buffer, strlen(buffer));

printf("the base 2 number converted to base 10 is: %d\n", result);
return 0;

}

if you are not familiar with C we are basically asking the user to enter a binary number and then the program call the function convert_to_base10() where the conversion actually happen based on this table :

each positions of the binary number correspond to 2 to the power of the position,( the positions start at 0) so the first bit to the right is 2⁰ which is equal to 1, the second position from the right is 2¹ = 2, and so forth.

The program multiples the value of the position with the bits value which might be 1 or 0, and keeps adding the results like this:
( 2⁰ * 1) + ( 2¹* 0) + ( 2² * 0 ) + ( 2³ * 0) + ( 2⁴ * 0) + ( 2⁵ * 0) + ( 2⁶ * 1) + ( 2⁷ * 0) + ( 2⁸* 1)

let’s try to run the program with the binary value in the table:

and that’s right 321 in base 10 is equal to 101000001

i am sure there are some easiest way to achieve the conversion, but this works too, and I am positive that this program might have potential or structural bug as well, but this is not the article point.

i was testing the program and i wanted to see if the following output was correct, and i thought, LET`S ASK CHAT-GPT! here’s my output:

output of the C program.

then i asked chat to do the conversion:

then i checked on different platform and the result that my program outputted is right, I have to admit that at first i was like, WHAT ? did i screw up big time ?

while Chat-gpt is an amazing tool, you should always check its output because it is not necessarily right, and i had to ask 3 times to get the right answer, and studying and reading docs will always pay better than AI suggestions. Here the other prompts:

here the last one :

finally the correct one :

thanks for checking in, I will see you soon with an article about pointers in C, speaking of C, you should check this channel https://youtu.be/3T3ZDquDDVg?si=Hp6UVTeNMCzTPDIP , if you do not follow it already, I think it is a great tool to learn lots of cool stuff, BYE!

--

--

No responses yet