Jake
Jake

Reputation: 16837

Convert hex array in C to long in C to String in Java

I have a situation where I have an array of hex characters like the following:

// C code
char arr[4];
// Using printf with 0x%02x format specifier, I can see the following contents:
arr[0] --> 0xb2;
arr[1] --> 0x00;
arr[2] --> 0x27;
arr[3] --> 0x79;

The above code is in C. I need to convert this array into a long value. The long value has to be then sent into Java code, where it needs to be converted into a string.

C array ---> long value ---> Java String

The end goal is to get a string in Java initialized as shown below:

// Java code
String goal = "b2002779";

What would be the recommended way to do this ?

I tried to convert the C char array to long using this answer, but it returned 0. Any other suggestions ?

Upvotes: 1

Views: 737

Answers (2)

london-deveoper
london-deveoper

Reputation: 543

You could do the conversion on the c++ side. Use something like the following.

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

char map[16];

void convert(unsigned short decimal, char* buffer) {
  if (decimal > 255) {
    return;
  } else if (decimal < 16) {
    buffer[0]='0';
    buffer[0]=map[decimal];
  } else {
    unsigned short remainder=decimal%16;
    unsigned short multiplier=(decimal-remainder)/16;
    buffer[0]=map[multiplier];
    buffer[1]=map[remainder];
  }

  printf("conversion %d to %s\n", decimal, buffer);
}

int main(int argc, char** argv) {
  map[0]='0';
  map[1]='1';
  map[2]='2';
  map[3]='3';
  map[4]='4';
  map[5]='5';
  map[6]='6';
  map[7]='7';
  map[8]='8';
  map[9]='9';
  map[10]='A';
  map[11]='B';
  map[12]='C';
  map[13]='D';
  map[14]='E';
  map[15]='F';

  unsigned short arr[4];
  arr[0] = 0xb2;
  arr[1] = 0x00;
  arr[2] = 0x27;
  arr[3] = 0x79;

  printf("%i.%i.%i.%i\n",
         arr[0], 
         arr[1], 
         arr[2],
         arr[3]);

  static char buffer[9];

  for(int x=0; x<4; x++) {
    static char buffer1[3];
    memset(buffer1, 0, sizeof(buffer1));
    convert(arr[x], buffer1);
    strcat(buffer, buffer1);
  }

  printf("%s\n", buffer);

  return 0;
}

Upvotes: 0

rosghub
rosghub

Reputation: 9254

You can append these unsigned char values using sprintf, then convert to a base 10 long using atol

unsigned char b[] = { 0xb2, 0xa1, 0xc3 };

char s[20];
sprintf(s, "%d%d%d", b[0], b[1], b[2]);

long n = atol(s);

Then with the either 32 or 64 bit value (depending on your system) in base 10 in java, you can use Integer.toHexString to convert to a hex string.

Upvotes: 1

Related Questions