-2

I am trying to compute the hash value of some words using sha256, but when I use sha256_update() function,

typedef unsigned char BYTE;
BYTE text1[] = {"abcd"};
sha256_update(&ctx, text1, strlen(text1));

use strlen() on BYTE type will give me some warnings, so I want to know what is the proper way to get the length of the text1?

In file included from /usr/include/memory.h:29:0,
             from sha256-test.c:16:
/usr/include/string.h:384:15: note: expected ‘const char *’ but argument is of type ‘BYTE {aka unsigned char}’
 extern size_t strlen (const char *__s)
           ^~~~~~
sha256-test.c:54:36: warning: pointer targets in passing argument 1 of ‘strlen’ differ in signedness [-Wpointer-sign]
  sha256_update(&ctx, text1, strlen(text1));
Vincent Zhou
  • 141
  • 2
  • 10

1 Answers1

2

It looks like the typedef name BYTE is defined the following way

typedef unsigned char BYTE;

In this case cast the type unsigned char * to type char * (or to const char * ) because there is no implicit conversion between the types. For example

BYTE text1[] = {"abcd"};
sha256_update(&ctx, text1, strlen( ( char * )text1 ) );

Take into account that for such initialization of the array

BYTE text1[] = {"abcd"};

(when the size of an array is determinated by its initialization with a string) you can get the length of the string also the following way

sizeof( text1 ) - 1

Here is a demonstrative program

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

typedef unsigned char BYTE;

int main( void )
{
    BYTE text1[] = {"abcd"};
    size_t n = strlen( ( char * )text1 );

    printf( "n = %zu\n", n );
    printf( "sizeof( text1 ) - 1 = %zu\n", sizeof( text1 ) - 1 );
}

Its output is

n = 4
sizeof( text1 ) - 1 = 4
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335