Please find the below code snippet.
unsigned char bInput[20];
unsigned char cInput[20];
From a function, I get a binary data in bInput
and I determined its length using strlen(bInput)
.
I converted bInput
which is in binary to ASCII and stored in cInput
and printed its length. But both are different.
I am new to programming. Please guide regarding its behaviour.
result wont be same for both cases.
Below is one sample scenario:
Null is valid UTF-8, it just doesn't work with C 'strings'.
char temp[8];
buf = "abcde\0f";
What we have here is a buffer of length 8, which contains these char values:
97 98 99 100 101 0 102 0
here,strlen(temp) is equal to 5 as per strlen design,however,The actual length of the buffer is eight.
Function strlen
returns the index of the first character in memory with a value of 0 (AKA '\0'
), starting from the memory address indicated by the input argument passed to this function.
If you pass a memory address of "something else" other than a zero-terminated string of characters (which has been properly allocated at that memory address), then there's a fair chance that it will result with a memory-access violation (AKA segmentation fault).
strlen()
counts each byte untill it reaches NULL character ('\0'
that means value of a byte is zero). So if you are getting different length for binary and ascii characters means you need to check the below two points in your conversion logic,
- what you are doing if binary value is zero.
- whether you are converting any nonzero binary value to zero.