Does strlen return same value for a binary and ascii data

隐身守侯 提交于 2019-12-06 15:33:38

问题


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.


回答1:


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.




回答2:


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).




回答3:


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.


来源:https://stackoverflow.com/questions/24596189/does-strlen-return-same-value-for-a-binary-and-ascii-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!