Converting the Javascript UUID function to C code

I'm in the process of converting a unique UUID creation formula from JavaScript to C. The challenge lies in finding a solution without relying on extensive crypto library dependencies that are typically associated with existing C libraries.

JavaScript:

   function generate(prefix)
   {
    return (prefix + 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx')
        .replace(/[xy]/g, function (c) {
    
          var r = Math.random() * 16 | 0;
          var v = (c === 'x') ? r : (r & 0x3 | 0x8);
    
          return v.toString(16);
        });
    }
    console.log(generate("Hello"));

Answer №1

This function is designed to generate a random hexadecimal character.

Here's the implementation in C:

char hex_digit(char c)
{
    char* hexes = "0123456789abcdef";
    int r = rand() % 16;
    int v = c == 'x' ? r : (r & 0x3 | 0x8);
    return hexes[v];
}

It then replaces occurrences of 'x' and 'y' with random hexadecimal digits in a given string:

void hexify(char* str)
{
    while (*str)
    {
        if (*str == 'x' || *str == 'y')
            *str = hex_digit(*str);
        str++;
    }
}

Testing this function:

int main()
{
    char input[] = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
    hexify(input);
    printf("%s\n", input);
    return 0;
}

The output will be something like:

df694488-87ff-4b1c-9a69-c57444f58497

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Communication both ways between Python and Javascript

I've created a webpage with HTML and JavaScript, but I'm having trouble passing input values as arguments to the Python backend through Node.js. Does anyone know of a better solution for this issue? ...

Scroll through the page effortlessly

Is there a way to make a specific div on my page automatically start scrolling down and then back up when the page loads? This is the JavaScript code I have written: <script> function scrollDownAndUp(speed) { $('#scrollingcontent').anim ...

Is there a way to determine if a field has been interacted with and meets validation criteria using VeeValidate?

I'm attempting to retrieve the validation flags from a computed property: computed: { isFormValid() { let isValid = this.$validator.fields.some(field => { console.log(field.flags); return field.flags.touched || field.flags.invali ...

Struggling to implement a JavaScript dynamic menu on an HTML website and encountering persistent difficulties

Alright, let's take a look at the HTML code I've put together: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Menus</title> <script type="text/javascript" src="Cities.js"> </scr ...

The content within the tab is currently being loaded

Incorporating jQuery UI tabs into my webpage, I encounter a delay of 5-6 seconds when clicking on a tab as it triggers an ajax call for preparing and displaying content. The screen stays idle during this time, leading to user confusion. I am seeking a sol ...

What is the process for accessing jQuery methods in Node.js?

When working on the client side, using Object.keys($.fn) (or Object.keys(jQuery.fn)) is a simple way to retrieve jQuery functions as an array. But how can I achieve the same result of getting this array with the jquery package from npm? I attempted: re ...

Unlocking the secrets of parsing JSON within a script tag using Laravel and AngularJS

I am facing some confusion as I attempt to use JSON with Angular and Laravel (v5.2.11) Here is my plan: 1. Send JSON to a blade file 2. Retrieve JSON within a script tag and assign it to a variable 3. Display each data In order to avoid duplicating ...

Expanding the filtering capabilities in AngularJS with additional selection options

I'm working with a repeater and implementing a filter to query the items, like this: ng-repeat="item in items | filter:query" Now, I want to incorporate a select option as an additional filter. Any ideas on how to integrate this with the existing fi ...

What is the process for invoking JSON RPC in ODOO?

odoo.define('custom_appointment_module.appointment', function(require) { "use strict"; var ajax = require('web.ajax'); var core = require('web.core'); $(document).ready(function() { $(' ...

Streamlining JavaScript in ASP.NET

I'm starting to dive into the world of ASP.NET after being a loyal desktop application supporter for years. One thing that's been bothering me is the cluttered HTML with all the inline JavaScript. Is there a way to have the generated script stor ...

Frontend update: Changing the display format for dates

Received from the backend is an array of objects (leavedays)- var leavedays = [{"_id":"62d544ae9f22d","season":2022,"name":"LEAVEDAY1","dateFrom":"2022- 07-26T00:00:00.000Z","date ...

yii2: Gridview selected rows processing issue - ajax post data missing

Within my yii2 application, I am looking to group machines into specific machine groups. Due to the large number of machines, users must select them via a checkbox column in a kartik-gridview, which offers sorting and filtering capabilities that a standard ...

Here is a way to showcase an HTML input element using JavaScript: by using the following code: .html('<input type="text" />')

Can someone assist me with displaying an input HTML code using JS when I select an option? Here is the HTML code: <select id="mystuff"> <option value="" disabled selected>Choose by:</option> <option value="Dealer" >De ...

Using the embedded R.dll, a program written in C crashes when attempting to call the standard C function fprintf()

Currently, I am using MSVC2013 Update 5 along with the import library for R.dll from Revolution R 3.2.2 x64 in order to compile a custom version of Rserve (). This particular version of Rserve utilizes an embedded R.dll and the CRT type is multithreaded de ...

Attempting to implement form validation on my website

Recently watched a tutorial on basic form validation on YouTube, but I'm encountering an issue where the error messages from my JavaScript file are not displaying on the website during testing. I have set up the code to show error messages above the l ...

Receive the most recent query in a Nuxt plugin following the completion of page loading

So, here's the issue - I have a plugin containing some functions that are supposed to update URL queries. However, every time I run $global.changePage(2) or $global.changeLimit(2), the console.log(query) outputs an empty object and doesn't show t ...

Is there a way to turn off the #warning notification in GCC?

Within GCC, there exists a pre-processor directive known as #warning, designed to issue warnings at compile time by attaching a specific string. According to the GCC documentation, this warning can be suppressed using the -Wno-cpp flag. However, in my expe ...

Dynamic HTML5 elements in constant motion

I'm interested in creating an HTML5 canvas that features bouncing circle and square elements that interact with each other, potentially spinning upon collision. The best example I've come across so far is located at this link. var canvas = docu ...

Acquire Content using jQuery and Navigate page horizontally

I am trying to achieve a unique effect by capturing content x and horizontally scrolling the page while the mouse is in motion, similar to swiping on a tablet. It seems simple enough.. Capture clientX on mousedown, ScrollLeft by ClientX while moving, Di ...

include the ReactToastify.css file in your project using the import statement

Error in file path C:\Users\User\Documents\GitHub\zampliasurveys_frontend\node_modules\react-toastify\dist\ReactToastify.css:1 ({"Object.":function(module,exports,require,__dirname,__filename,jest){:ro ...